簡體   English   中英

while循環后的語句未執行

[英]Statement after while loop isn't executed

我遇到了while循環問題。 while循環后的語句沒有執行,我也不知道為什么。 我是C ++的新手,無法弄清楚這一點。 我試圖將一些單詞作為用戶的輸入並將它們存儲在字符串向量中,僅僅是為了練習。 這是我的代碼:

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>

using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

int _tmain(int argc, _TCHAR* argv[])
{
    vector<string> list;
    string word;

    while( cin >> word )
    {
        list.push_back(word);
        cout << "Added " << word << endl;
    }

    cout << endl;
    cout << "Done" << endl;

    system( "PAUSE" );
    return EXIT_SUCCESS;
}

當我運行這個控制台應用程序時,我可以看到while循環中的語句被執行並且消息“已添加”但是沒有顯示消息“已完成”。 我已經通過在while循環之后指定其他語句來嘗試這個(就像for循環獲取和顯示來自相同字符串向量的值)但是在執行while循環之后沒有語句。 只執行while循環之前和之內的語句,我不知道為什么。

只要輸入有效字符串,循環就會繼續。 只是輸入一個空行將無法工作,因為輸入操作符將阻塞,直到它讀取非空白字符。 您需要通過按CTRL-Z (文件結束鍵盤快捷鍵)實際“終止”字符串。


如果要檢測空行並將其用於終止條件,則需要使用std::getline

std::string line;
while (std::getline(std::cin, line) && !line.empty())
{
    ...
}

你的while循環沒有結束,因為cin總會返回soemthing != 0 ,這意味着你被困在無限循環中。 你需要的是循環中執行休息的另一個條件:

string stop_string = "exit";

while( cin >> word )
{
    if ( stop_string.compare(word) )
        break;

    list.push_back(word);
    cout << "Added " << word << endl;        
}

或者您可以使用std::getline來檢測像Joachim Pilebord建議的空行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM