不幸的是,对于 C,我是一个完全的新手。我正在尝试读取一个格式如下的文本文件
one two three
two one three
three one
我需要读取一行中的第一个字符串(所以如果第一行是“一个”,那么我会与一个变量进行比较。如果它匹配,那么我需要使用字符串的其余部分,因此,如果字符串一匹配,我需要使用“二”和“三”(分别作为它们自己的字符串)。 如果没有匹配项,我将转到下一行,依此类推。
这是我目前的代码,但它似乎不起作用。在评论中我认为代码在做什么。
char temp[] = "three";
while(!feof(file)){ //Go until end of file is reached
fgets(line, 100, file); //Grab the line
string_token = strtok(line, " "); //Tokenize the line
strcpy (compare_to, string_token); //Copy first token into a string variable
if (strcmp(compare_to, temp) == 0){ //Compare string with a predefined temp variable
while (string_token != NULL) { //If it was a match then we go until tokens end (which would be end of the line from a file)
printf("%s has the following: %s\n", temp,compare_to );
string_token = strtok(NULL, " ");
}
}
}
最佳答案
Reading file line by line, read first string, if match then use rest of the line, otherwise move to next line
在所有情况下,代码都需要读取整行——这只是一个如何使用输入的问题。
不要使用这个problematic code
// while(!feof(file)){
// fgets(line, 100, file);
相反
while(fgets(line, sizeof line, file)) {
现在解析字符串,将\n 添加到定界列表中。
int count = 0;
string_token = strtok(line, " \n");
// compare the the i'th `compare_to[i]` or
// what ever fulfills "then I do a comparison with a variable"
if (string_token != NULL && strcmp(compare_to[i], string_token) == 0){
printf("<%s>\n", string_token );
string_token = strtok(NULL, " \n");
count++;
}
}
关于c - 逐行读取文件,读取第一个字符串,如果匹配则使用该行的其余部分,否则移至下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48197630/