简体   繁体   English

为什么Loop永不结束?

[英]Why does this while Loop never end?

So I feel that I am close to solving a programming assignment that takes the most used word of each line and prints it on a line. 因此,我觉得我即将解决编程任务,该任务需要占用每行中最常用的单词并将其打印在一行上。 So for example: 因此,例如:

I am a man, am right?
I don't know if i like that.
It's okay to not feel okay.

Would print: "am i okay" (punctuations and case are ignored for the assignment) 将会打印:“我可以”(标点和大小写被忽略)

This is what I have done so far, but the problem is that the while loop that scans the lines never terminates and thus never prints the output in the external for loop. 到目前为止,这就是我所做的事情,但是问题是,扫描行的while循环永远不会终止,因此也永远不会在外部for循环中输出输出。 Anybody see where I went wrong? 有人看到我错了吗?

string line;
vector<string> result;
while(getline(cin,line)){     //on each line

}

Your loop is correct as written; 你的循环是正确的; you just don't know how to signify the end of input. 您只是不知道如何表示输入结束。 You're sitting there waiting for the program to progress, but the program is sitting there waiting for you to give it more input. 您坐在那里等待程序进展,但是程序坐在那里等待您提供更多输入。

Press Ctrl+D (Linux) or Ctrl+Z (Windows) to send the EOF character/signal/potion to end the loop. 按Ctrl + D(Linux)或Ctrl + Z(Windows)发送EOF字符/信号/部分以结束循环。

This way, all the common shell techniques like file redirection and pipes will also work. 这样,所有常见的shell技术(例如文件重定向和管道)也将起作用。

Introducing artificial means like a double-newline or some magic command is non-conventional and makes your program harder to automate. 引入人工手段(例如双换行符或某些魔术命令)是非常规的,这会使程序更难以自动化。 (And making your program magically know that one of the newlines came from a keyboard hit rather than copy/pasting, is just not possible. Nor do you want it to be! That breaks a ton of valuable abstractions.) When writing a command-line tool, stick to standard practices as much as possible. (要使您的程序神奇地知道其中的换行符是来自键盘击键而不是复制/粘贴,这是不可能的。您也不希望这样做!这会破坏大量有价值的抽象。)编写命令时,线工具,尽可能遵守标准惯例。

Currently your program is waiting for an EOF character which indicates the input has ended. 当前,您的程序正在等待EOF字符,该字符指示输入已结束。 If you are running this and entering the input from the command line, you can manually insert an EOF by pressing Ctrl+D on *nix, or Ctrl+Z on windows. 如果正在运行此命令并从命令行输入输入,则可以通过在* nix上按Ctrl + D或在Windows上按Ctrl + Z来手动插入EOF。 This will cause your program to break out of your getline loop. 这将导致您的程序脱离getline循环。

If you would rather not do that, you need a way to break out of the getline loop, otherwise it will continue to run in that loop. 如果您不想这样做,则需要一种方法来打破getline循环,否则它将继续在该循环中运行。

A nice idea might be detecting an empty line, so pressing enter twice ends the loop: 一个好主意可能是检测到一个空行,因此按Enter键两次将结束循环:

while(getline(cin,line)){     //on each line
    if(line == "")
        break;
    ...
}

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

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