需要用户输入串/检查字符串长度(C++)
我需要从用户(仅5)接受5个的一串数字。 我应该使用需要用户输入串/检查字符串长度(C++)
istringstream
对于相同的?
我不能摆脱这样的事情?
int main()
{
char *InputMain;
InputMain=(char *)malloc(5+1);
cout << "Enter the number : " <<endl;
cin.getline (InputMain, 5, '\n'); // Input goes into InputMain
cout << "The number entered is : " << InputMain <<endl;
cin.get();
}
然后是下一部分..
你怎么我确保用户仅输入5个字符?也许如果用户输入超过5个字符,我应该显示一个警告,说只允许5个字符。
还有一个问题,因为这本质上是一个字符串,我需要验证输入只有数字通过解析字符串中的每个字符并检查相应的ASCII值(数字)..这种方法是正确的吗?
不幸的是,限制输入的字符的数量在C++中没有可移植的方法。但是无论您使用哪种平台都会提供一些机制:例如在Windows上,查找Console functions。
如果用普通的旧C++输入输出流输入去从cin
,这是一个好主意,阅读的初始文本为std::string
使用istream& getline(istream&, string&)
- 这将防止缓冲区溢出,因为string
S调整是必要的。 (您涉及getline(InputMain, 5, '\n')
码在技术上是安全的,因为它不会读取超过5个字符为InputMain
,但是这个代码是脆弱的 - 如果你以后决定要6个字符,你可以很容易忘记更新您的来电malloc()
,领先。死机另外,你需要记住free(InputMain)
但正如我所说,使用string
代替)
关于解析:。
无论您使用getline(cin, str)
或读取输入到string
一些特定平台的代码,一旦它在那里,你需要以数字的形式出来。这就是istringstream
类是有用的 - 它可以让你把一个现有string
作为流从阅读,因此,您可以使用格式化的输入>>
操作:如果您使用C++输入输出流
string str;
if (!getline(cin, str)) {
cerr << "Something went seriously wrong...\n";
}
istringstream iss(str);
int i;
iss >> i; // Extract an integer value from the stream that wraps str
if (!iss) {
// Extraction failed (or a more serious problem like EOF reached)
cerr << "Enter a number dammit!\n";
} else if (i < 1000 || i > 9999) {
cerr << "Out of range!\n";
} else {
// Process i
}
,你可实际上只是从cin
直接提取的,而不是通过string
去和istringstream
:
int i;
cin >> i; // Extract an integer value from cin
然而,这可能会有细微的不良影响;值得注意的是,用户输入的行上的任何附加字符(特别是按Enter键时输入的'\n'
)将保留在输入缓冲区中,以便在接下来的<<
操作中读取。通常这并不重要,但有时确实如此:例如如果你跟进cin.get();
,预计这将等待一个按键,它不会 - 它只是读取'\n'
(或第一个非数字字符的用户输入)。
你的意思是我应该使用这样的事情? #include
这听起来很像功课 – lothar 2009-04-17 17:07:51