gpt4 book ai didi

c++ - C++ 中的过度循环 (Cout)

转载 作者:太空宇宙 更新时间:2023-11-04 13:53:53 24 4
gpt4 key购买 nike

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
char hold;
string name;
char num1;
char num2;

int main() {
cout << "Hello!\n";
cout << "Tell me your name?: ";
cin >> name;
cout << "Well well well, if it isn't "<< name << "!\n";
cout << "Enter a NUMBER " << name << ": ";
cin >> num1;
while(!isdigit(num1)) {
cout << "Enter a NUMBER " << name << ": ";
cin >> num1;
}
cin >> hold;
system("pause");
return 0;
}

enter image description here

问题是,它覆盖了 cout。我该如何解决?

谢谢。

最佳答案

更好的方法是使用std::stringstream(注意:包含sstream)

    int getNumber()
{
std::string line;
int i;
while (std::getline(std::cin, line))
{
std::stringstream ss(line);
if (ss >> i)
{
if (ss.eof())
{
break;
}
}
std::cout << "Please re-enter your input as a number" << std::endl;
}
return i;
}

这取代了您的 while 循环,您在询问号码后调用电话,因为您已经知道该怎么做。

关于c++ - C++ 中的过度循环 (Cout),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22388164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com