[英]Input by pressing enter once
我是一個初學者,如果問題令人困惑或表達不好,請對不起。 為了簡明扼要,您需要給出3個變量的值,並且輸入應在一行中給出。 例如,您按3 4 2而不在每個值后面都按Enter,而是在最后按它。 代碼將如何工作?
您的要求不明確。 請考慮使用RFC 2119樣式消除歧義。
如果可以在一行中給出3個值:
int a,b,c;
cin >> a >> b >> c;
如果必須在一行中給出三個值:
#include <string> // Edit: don't forget these headers
#include <sstream> // after those that you already include
...
string s;
getline(cin,s); // input one line
istringstream sst(s); // then parse that line
int a,b,c;
sst >>a>>b>>c;
抱歉,我有一段時間沒有登錄,但我自己回答了。 我的代碼在下面,感謝您的回答,也對我缺乏解釋感到抱歉。
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char a[100];
string c;
int b[3], j=0, i;
cin.getline(a,100);
c=a;
for(i=0; i<3; i++)
b[i]=0;
for(i=0; i<c.length(); i++)
{
if(isdigit(c[i]))
{
b[j]=b[j]+(c[i]-'0');
//cout<<b;
if(isdigit(c[i+1]))
b[j]=b[j]*10;
else
j++;
}
}
for(i=0; i<3; i++)
cout<<b[i]<<" ";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.