"函数getline"从文件中没有读取该行的第一个字符串

时间:2018-04-26 23:17:01

标签: c++ file-io

我有一个带字符串的文件" abc defg hij klmno" ,当我试图读取并修改它时,输出结果为" defg hij klmno"不知怎的,第一个字符串丢失了。任何想法?

int main(int argc, char **argv)
{
   ifstream myfile("C:\\sth.txt");
   string Ciphertext;
while (myfile>>Ciphertext)
{
    getline(myfile, Ciphertext);    
}


//some other code...

2 个答案:

答案 0 :(得分:1)

你读到Ciphertext的第一个条目,然后立即丢弃它并读取“其余的”如果该行。

while(myfile>>Ciphertext)
{
    getline(myfile, Ciphertext);
}

请改为尝试:

while(getline(myfile, Ciphertext))
{
    // logic for each line here
}

答案 1 :(得分:0)

Consider this code:

while (myfile>>Ciphertext)
{
    getline(myfile, Ciphertext);    
}

The expression in the while attempts to read the first white-space delimted string from the file into Ciphertext. It succeeds, reading abc, so it goes into the loop where it reads a line (up to the next newline) into Cipertext, replacing whatever is there. So it reads the rest of the first line defg hij klmno. It then goes back and tries to read another whitespace delimeted string, but that fails, as you're now at the end of the file. So the while loop ends, leaving defg hij klmno in Ciphertext