How do I iterate over cin line by line in C++?

后端 未结 4 747
别跟我提以往
别跟我提以往 2020-11-22 09:53

I want to iterate over std::cin, line by line, addressing each line as a std::string. Which is better:

string line;
while (getline         


        
4条回答
  •  情深已故
    2020-11-22 10:33

    Go with the while statement.

    See Chapter 16.2 (specifically pages 374 and 375) of Code Complete 2 by Steve McConell.

    To quote:

    Don't use a for loop when a while loop is more appropriate. A common abuse of the flexible for loop structure in C++, C# and Java is haphazardly cramming the contents of a while loop into a for loop header.

    .

    C++ Example of a while loop abusively Crammed into a for Loop Header

    for (inputFile.MoveToStart(), recordCount = 0; !inputFile.EndOfFile(); recordCount++) {
        inputFile.GetRecord();
    }
    

    C++ Example of appropriate use of a while loop

    inputFile.MoveToStart();
    recordCount = 0;
    while (!InputFile.EndOfFile()) {
        inputFile.getRecord();
        recordCount++;
    }
    

    I've omitted some parts in the middle but hopefully that gives you a good idea.

提交回复
热议问题