簡體   English   中英

std :: cin不接受輸入,程序立即關閉

[英]std::cin does not accept input, program closes immediately

我嘗試使用cin作為輸入來獲取字符串,並且它起作用了,但是當我嘗試在字符串之后立即獲取int作為輸入時,控制台將不要求它,並且程序關閉。 這是我的代碼:

#include <iostream>
#include <string>
using namespace std;

void main(void)
{ 
string a, b;
int c, d, e;

cout << "Enter two words \n";
cin >> a, b; 
cout << "Enter three int";
cin >> c, d, e;
cout << c*d;
}

這段代碼不會讓我輸入第二個輸入,但是在程序關閉之前,我可以看到第二個輸出。

您的代碼是錯誤的:

cin >> a, b;

不會給你你所期望的。 在您需要從cin讀取字符串的情況下,使用:

cin >> a;
cin >> b;

其他類型也一樣。

另請注意:

void main( void )

是不正確的。 main 必須返回一個int

int main( void )
{
    return 0;
}

cin >> a, b; 使用逗號運算符,該運算符從左到右評估不同的表達式。 結果與以下代碼相同:

cin >> a;
b;

當行cin >> c, d, e; 達到后,其評估結果類似:

cin >> c;
d;
e;

結果是,當第二個cin >> ...語句被求值時,您輸入的第二個單詞仍在輸入緩沖區中,它無需等待用戶的更多輸入即可完成。

這是錯誤的:

cin >> a, b; 

它應該是:

cin >> a >> b; 

同樣地:

cin >> c, d, e;

應該:

cin >> c >> d >> e;

確保將來啟用編譯器警告-這樣,編譯器可以為您指出許多類似的簡單錯誤。 當我在啟用警告的情況下編譯原始代碼時,我得到:

$ g++ -Wall junk.cpp
junk.cpp:5:1: error: 'main' must return 'int'
void main(void)
^~~~
int
junk.cpp:13:11: warning: expression result unused [-Wunused-value]
cin >> c, d, e;
          ^
junk.cpp:11:11: warning: expression result unused [-Wunused-value]
cin >> a, b;
          ^
junk.cpp:13:14: warning: expression result unused [-Wunused-value]
cin >> c, d, e;
             ^
3 warnings and 1 error generated.

由此很容易看出兩條cin行有問題,並且還需要將main的返回類型更改為int

嘗試:

int main(void)
{ 
string a, b;
int c, d, e;

cout << "Enter two words \n";
cin >> a >> b; 
cout << "Enter three int";
cin >> c >> d >> e;
cout << c*d;
}

暫無
暫無

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

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