我已经为这个错误苦苦挣扎了一段时间。我正在使用 Windows 10 和 code::blocks 16.01 MinGW。
我想将 c 与结束行字符进行比较。
我系统上的一个程序运行成功,只是为了跳过文件的标题行:
while(c!='\n')
{
c = fgetc(traverse);
if(c == EOF)
return(1);
}
使用
打开遍历的地方fopen("traverse.dat", "r");
但是,我的其他程序:
FILE * infile;
/* Open a large CSV */
infile = fopen("Getty_Megatem.csv", "r");
if(infile == NULL)
{
printf("no file");
return(EXIT_FAILURE);
}
char c = 0;
int i = 0;
/* Opens file successfully */
printf("File opened\n");
/* Count commas in first line */
while(c != '\n');
{
c = fgetc(infile);
if(c == ',')
i++;
if(c == EOF)
return(EXIT_FAILURE);
}
printf("Number of commas: %i\n", i);
fclose(infile);
return(EXIT_SUCCESS);
和
ifstream infile;
char c;
string mystr;
infile.open("ostring.dat");
// Skip a line
while (c!= '\n')
infile >> c;
getline(infile, mystr);
和(我真正想工作的那个)
ifstream emdata;
string firstline;
char c = 0;
int i = 0;
vector<double> vdata;
// redundancy
vdata.reserve(10000);
// There are ~ 300 doubles per line
emdata.open("Getty_Megatem.csv");
// Skip first line
getline(emdata, firstline);
while(c != '\n' && c != EOF)
{
emdata >> vdata[i] >> c;
cout << vdata[i] << ",";
i++;
if(i == 999)
{
cout << "\n\ni>9999";
break;
}
}
emdata.close();
return 0;
不成功,他们编译并执行然后永远读取流 - 或者直到达到我的最大迭代次数 9999。所有这些文件都包含新行。
最佳答案
当您应该使用未格式化输入时,您正在使用格式化输入来获取字符:
char c;
if (cin.get( c )) ...
或
int c;
c = cin.get();
if (c != cin.eof()) ...
>>>
运算符删除空格,包括换行符。
关于c++ - 逐个字符不一致地响应\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45334429/