无法在循环中读取Char/string
Unable to read Char/string in loop
这是一个非常简单的问题,一直困扰着我。在While循环中从一行中读取字符时,不会进行第二次读取。如果我使用cin>>name
,它可以正常工作,但我需要字符之间的空格。使用String
类也有同样的问题。
int main()
{
int i=0;
int intRate;
char name[20];
while(i!=3){
cout<<"Enter name";
gets(name);
cout<<"Enter Interest Rate: ";
cin>>intRate;
i++;
cout<<endl;
}
cout<<"name is : "<<name<<endl;
cout<<"Interest Rate is: " <<intRate;
}
因此,当我尝试在循环中键入字符"gets(name)"时,第一次它接受该字符,然后我也可以输入intRate
,但下次遇到循环i=1
时,我不能为name
键入任何内容,或者它不读取任何字符行,而是打印Enter Interest Rate
,并在下面的循环中读取intRate
。
但如果我不输入输入利率线,那么它就会再次开始平稳读取,如下所示:
char name[20];
while(i!=3){
cout<<"Enter name";
i++;
cout<<endl;
如果我这样做,它会读取循环中的所有字符。如果我在它下面再加一行打印,它就什么也看不出来了。
当您混合C和C++输入而不注意它们实际在做什么时,就会发生这种情况。
试试这个:
int main()
{
int i = 0;
int intRate = 0;
string name;
while (i != 3)
{
cout << "Enter name: ";
getline(cin, name);
cout << "Enter Interest Rate: ";
cin >> intRate;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
i++;
cout << endl;
}
cout << "Name is : " << name << endl;
cout << "Interest Rate is: " << intRate;
return 0;
}
或者这个:
int main()
{
int i = 0;
int intRate = 0;
string name, line;
while (i != 3)
{
cout << "Enter name: ";
getline(cin, name);
cout << "Enter Interest Rate: ";
getline(cin, line);
stringstream ss(line);
ss >> intRate;
i++;
cout << endl;
}
cout << "Name is : " << name << endl;
cout << "Interest Rate is: " << intRate;
return 0;
}
相关文章:
- 使用char类型将decimal转换为string,将string转换为decimal
- std::string 构造函数如何处理固定大小的 char[]?
- C++:将模板类型 char 转换为 std::string
- 从 std::string 到 std::array<char,size> 的 memcopy 额外数据是否是一种未定义的行为?
- "No suitable conversion function from 'std::string' to 'const char *' exists"
- 将"std::string {aka std::basic_string}"赋值中的不兼容类型<char>
- 错误:为"运算符 std::string {aka std::__cxx11::basic_string}"指定的返回类型<char>
- 为什么std::string没有(显式)const char*强制转换
- 将 std::string 转换为 const char* 用于 printf 消耗
- 我可以使用istream_iterator将<char>一些 istream 内容复制到 std::string 中吗?
- 让 'std::vector<unsigned char>' 从 'std::string' 中窃取内存
- 错误:请求从"Mstream"转换为非标量类型"std::string {aka std::basic_string<char>}"
- C :如何使用char / string 2D数组接受用户的1个以上的源性
- 我们应该在带有 char *func(char *string) 的函数中返回什么?需要简要说明这与 c 中的 char
- C++ 从 char* 到 char 的转换无效 (char* = *string.begin() )
- 无法在循环中读取Char/string
- 当我将char* string赋值给std::string时,可以释放它的内存吗?
- C char string和stint .h uint8_t在嵌入式系统中的兼容性
- 如何在c++中将LPBYTE转换为char */string
- 如何在等待用户输入int, float或其他类型时拒绝输入char/string