[英]How can I save a string input with blank space in c++ (I am using if else statement)
所以我正在嘗試制作一個文本乘法器,這是代碼
#include <iostream>
using namespace std;
int main()
{
bool m, n;
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin >> x;
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
一切都很好,直到我知道它沒有用空格保存文本輸入我搜索了如何用空格存儲字符串輸入然后更改了代碼但它沒有用。 更改后的代碼是
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
請幫忙
如果我明白你想做什么,你需要讀取 integer 值,清除operator>>
留在stdin
中的剩余'\n'
,然后使用getline()
讀取你想要乘以的文本,例如
#include <iostream>
#include <limits>
using namespace std;
int main()
{
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
if (!(cin >> y)) { /* validate stream-state after EVERY input */
std::cerr << "error: invalid integer input.\n";
return 1;
}
/* clear remaining '\n' from stdin (and any other characters) */
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "enter the text you want to multiply : ";
if (!getline (cin, x)) { /* validate stream state */
std::cout << "user canceled input.\n";
return 0;
}
for (int a = 1; a <= y; ++a)
cout << x << endl;
return 0;
}
注意:使用isdigit(y)
是多余的。 如果您正確驗證輸入,則只需在讀取后檢查流狀態即可確定在讀取時是否輸入了有效的 integer。 如果設置了失敗位,則用戶沒有輸入有效的failbit
。
雖然對於測試代碼來說很好,但您需要查看為什么“使用命名空間標准;” 被認為是不好的做法?
示例使用/輸出
$ ./bin/multiplytext
enter how many times you want to multiply the text : 3
enter the text you want to multiply : my dog has fleas
my dog has fleas
my dog has fleas
my dog has fleas
如果我誤解了您的目標,請告訴我,我很樂意進一步提供幫助。
從這個答案可以看出,您正在混合>>
運算符和getline()
這會導致同步問題,因為getline
不等待輸入刷新。
你可以打電話
cin.ignore();
或者
cin.clear();
cin.sync();
就在getline()
之前。
補丁代碼:
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.ignore();
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.