c++ - 逐个字符不一致地响应\n

标签 c++ windows newline codeblocks

我已经为这个错误苦苦挣扎了一段时间。我正在使用 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/

相关文章:

c++ - 代码块编译不可执行

Eclipse 和 Windows 换行符

git - Git 中的行结尾搞砸了 - 如何在巨大的行结尾修复后跟踪另一个分支的更改?

matlab - fprintf 不打印新行

c++ - 在 C++ 中哪种返回值的方式更快?

c++ - cout 时 cstring 上的额外字符

c++ - "Connection was broken"UDT 错误(基于 UDP 的数据传输协议(protocol))

windows - 使用命令行参数关联文件扩展名

c++ - 已删除 "general"案例的专用模板函数无法使用 g++ <=4.8.0 和 clang++ 编译

c++ - 如何编译和运行在 Windows 10 上使用 libev 的示例程序