Suppose there is a file, each row of the file consists of n integers, the integers are separated by a space, and the file has a total of M lines, but N,m is not known beforehand. How to read one row of integers from a file into an array at a time.
Can be divided into two steps: 1, first read a line of strings from a file, 2, and then parse out the integer from this line of string.
For the first step, we can have C, C + + two styles of practice
C Style:
FILE *FP = fopen ("Input.txt", "R");
Char buf[10000];
while (Fgets (BUF, 10000, FP))
{
//resolves an integer from buf
}
C + + Style:
Ifstream infile ("Input.txt");
string S;
while (Getline (infile, s))
{
//resolves an integer from S
)
After testing if the time to parse integers is not considered, the two methods are not time-consuming, indicating that getline and fgets efficiency are basically the same.
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/
For the second step, the integer is parsed from a single line of string, and the following provides the method in 3, in order to be simple, we simply return the number of integers parsed from the string and do not put them in an array
Method 1: Use string flow Istringstream
int GetInt (string &s)
{
istringstream iss (s);
int num, res = 0;
while (ISS >> num)
res++;
return res;
}
Method 2: Using the STRSTR function and the Atoi function
int getInt (const char *buf)
{
const char *loc = BUF;
int res = 0;
Atoi (BUF);
loc = Strstr (buf, "");
while (Loc!= NULL)
{
atoi (loc+1);
res++;
loc = Strstr (loc+1, "");
}
return res;
}
Method 3: Using the Strtok function and the Atoi function
int getInt (char *buf)
{
char *p = strtok (buf, "");
int res = 0;
while (p)
{
atoi (p);
res++;
p = strtok (NULL, "");
}
return res;
}
These three methods are time-consuming, Method 2 and Method 2 are basically the same (Method 3 has a slightly more time), Method 1 is almost 2 times the method 10 times
Author: cnblogs Tenos