我想从文件(“input.txt”)输入以下行:
a 1,2,3,4,5,6
b 1,8
(即一个字符后跟一个空格,然后是一个用逗号分隔的数组)
我试过以下代码:
int main(int argc, char *argv[])
{
std::vector<int> arr;
FILE *file = fopen("input.txt","r");
while(!feof(file))
{
for(int i = 0; i < arr.size(); i++)
{
fscanf(file,"%s %d,",str,&arr[i]);
}
}
}
让我知道这样做的正确方法,因为它显示了垃圾值
首先是Manisha,您正在目睹不寻常的代码行为,因为您使用过的while
循环永远不会停止。让我以一种非常简单的方式告诉你原因。你在while
循环中指定的停止条件,即feof()
表示是否有人试图读取文件末尾。但你永远不能读PAST文件的末尾,这意味着while
循环永远不会停止。
找到另一种阅读文件的方法。还有很多其他方法,其中一种我在下面显示:
while (fgets(line, sizeof(line), file)) {
/* note that fgets doesn't strip the terminating \n(new line character) */
...
}
if (ferror(file)) {
/* IO failure */
} else if (feof(file)) {
/* format error (not possible with fgets, but would be with fscanf) or end of file */
} else {
/* format error (not possible with fgets, but would be with fscanf) */
}
这应该是C还是C ++?您使用的是C ++数据类型(std::vector
),但使用的是C I / O例程。您还没有为str
指定类型。
假设您的意思是使用C I / O例程,您可以执行以下操作:
char str[SOME_LENGTH+1]; // where SOME_LENGTH is how big you expect the string to be
/**
* Get the string at the beginning of the line; scanf should return 1
* on a successful read.
*/
while ( scanf( "%s", str ) == 1 )
{
size_t i = 0;
/**
* Read the sequence of integers and commas. We consume the character
* immediately following the integer, but don't assign it (the %*c
* specifier). So we'll consume the comma or newline following
* the integer. Since a letter isn't part of a decimal integer,
* we'll stop scanning at the beginning of the next line.
*/
while( scanf( "%d%*c", &arr[i++] ) == 1 )
; // empty loop
}
注意:这假设您的输入表现良好,并且数字和后面的逗号之间没有空格(即,您没有像1, 2 , 3
这样的内容)。