简体   繁体   English

无法使用>>运算符从文件中正确读取数据

[英]Data not correctly read from file using >> operator

I have a data file with 3 columns in each row: Two 3 character strings and a float like this. 我有一个数据文件,每行3列:两个3个字符串和一个这样的浮点数。

AAA BBB 699.25

I'm trying to read in the data using ifstream like this: 我正在尝试使用ifstream读取数据,如下所示:

    ifstream input;

    char str1[3], str2[3];
    float num;

    input.open("data.txt");

    input >> str1 >> str2 >> num;
    cout << str1 << endl;
    cout << str2 << endl;
    cout << num << endl;

However the output I get with Clang is: 但是我用Clang得到的输出是:

(blank)
BBB
699.25

Or Intel C++ this: 或英特尔C ++:

AAABBB
BBB
699.25

If I get the individual variables without multiple ">>" operators all works correctly. 如果我得到的变量没有多个“ >>”运算符,则所有变量都可以正常工作。 I'm guessing I don't understand how >> works and it's overwriting my data in the buffer as I push more into the array. 我猜我不明白>>的工作方式,并且当我将更多内容推入数组时,它正在覆盖缓冲区中的数据。

The string "AAA" is not three characters long. 字符串"AAA"长度不超过三个字符。 You have three visible characters and one non visible null character. 您有三个可见字符和一个不可见的空字符。 This means to hold "AAA" you need four characters worth of storage. 这意味着要持有"AAA"您需要四个字符的存储空间。 If you use a std::string this becomes a non issue as it takes care of things like this for you. 如果您使用std::string这将成为一个非问题,因为它将为您处理类似的事情。 Since you just have this tagged as C++ I would change char str1[3], str2[3]; 由于您只是将此标签标记为C ++,因此我将更改char str1[3], str2[3]; to std::string str1, str2; std::string str1, str2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM