在Java中,可以使用它:
Scanner s = new Scanner (System.in);
String x = s.next();
if(x == null || x.length() == 0)
System.out.println("Please enter something") ;
如果用户点击 ENTER 键而没有输入任何内容,则说“请输入内容”。
如何使用Codeblocks或Visual Studio在C ++中执行此操作?
答案 0 :(得分:2)
C ++中的等价物或多或少:
#include <cstddef>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
string something;
bool more = true;
cout << "Enter something: ";
while (more) {
getline(cin, something);
if (something.empty()) {
cout << "Please enter something: ";
}
else {
more = false;
}
}
cout << "You entered '" << something << "'." << endl;
return EXIT_SUCCESS;
}
答案 1 :(得分:1)
我相信Scanner
会解析以空格分隔的项目
在C ++中,您需要首先阅读整行,然后将其拆分
像这样:
std::string x;
while (std::getline(std::cin, x) && x.empty())
{
std::cout << "Please enter something" << std::endl;
}
std::istringstream is(x);
std::string y;
while (is >> y)
{
// Do something with each "part".
}