简体   繁体   English

需要用户输入字符串/检查字符串长度(C ++)

[英]Need user to input string /check string length (C++)

I'll need to accept a string of 5 numbers from the user (only 5). 我需要接受来自用户的5个数字的字符串(仅5个)。 Should I use 我应该用吗?

istringstream 

for the same ? 对于相同的 ?

Can't I get away with something like this ? 我不能逃避这样的事情吗?

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();
}

Then comes the next part.. 然后是下一部分..

How'd I make sure the user inputs only 5 chars? 我如何确保用户只输入5个字符? And maybe if the user enters more than 5 chars, I should display a warning saying only 5 chars allowed.. 也许如果用户输入超过5个字符,我应该显示警告说只允许5个字符..

One more question, since this essentially is a string, I'll need to validate the input to be only numbers by parsing through each char in the string and checking against respective ASCII values (for numerals).. Is that approach the right thing? 还有一个问题,因为这本质上是一个字符串,我需要通过解析字符串中的每个字符并检查相应的ASCII值(对于数字)来验证输入只是数字。这种方法是正确的吗?

Unfortunately there is no portable way to restrict the number of characters input in C++. 遗憾的是,没有可移植的方法来限制C ++中输入的字符数。 But whatever platform you are using will provide some mechanism: for example on Windows, look up Console functions . 但无论您使用什么平台都会提供某种机制:例如在Windows上,查找控制台功能

If you do go with plain old C++ iostreams input from cin , it's a good idea to read the initial text into a std::string using istream& getline(istream&, string&) -- this will prevent buffer overflows, because string s resize as necessary. 如果您使用cin普通旧C ++ iostream输入,最好使用istream& getline(istream&, string&)将初始文本读入std::string - 这样可以防止缓冲区溢出,因为string根据需要调整大小。 (Your code involving getline(InputMain, 5, '\\n') is technically safe in that it won't read more than 5 characters into InputMain , but this code is fragile -- if you later decide you want 6 characters, you could easily forget to update your call to malloc() , leading to crashes. Also, you need to remember to free(InputMain) . But as I said, use string instead.) (你的代码涉及getline(InputMain, 5, '\\n')在技​​术上是安全的,因为它不会在InputMain读取超过5个字符,但是这段代码很脆弱 - 如果你以后决定要6个字符,你可以很容易忘记更新你对malloc()调用,导致崩溃。另外,你需要记住free(InputMain) 。但正如我所说,使用string代替。)

Regarding parsing: 关于解析:

Whether you read the input into a string using getline(cin, str) or some platform-specific code, once it's in there you need to get it out in the form of a number. 无论您是使用getline(cin, str)还是某些特定于平台的代码将输入读入string ,一旦它在那里,您需要以数字的形式将其输出。 This is where the istringstream class is useful -- it lets you treat an existing string as a stream to read from, so you can use the formatted input >> operator: 这是istringstream类很有用的地方 - 它允许您将现有string视为要读取的流,因此您可以使用格式化的input >>运算符:

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
}

If you're using C++ iostreams, you can actually just extract directly from cin instead of going via a string and an istringstream : 如果您正在使用C ++ iostream,您实际上可以直接从cin提取,而不是通过stringistringstream

int i;
cin >> i;    // Extract an integer value from cin

However this can have subtle undesirable effects; 然而,这可能会产生微妙的不良影响; notably, any additional characters on the line typed by the user (in particular the '\\n' typed when they press Enter) will remain in the input buffer to be read by the next << operation. 值得注意的是,用户键入的行上的任何其他字符(特别是按Enter键时键入的'\\n' )将保留在输入缓冲区中,以供下一个<<操作读取。 Often this doesn't matter, but sometimes it does: eg if you follow up with cin.get(); 通常这并不重要,但有时它确实如此:例如,如果你跟进cin.get(); , expecting that this will wait for a keypress, it won't -- it will just read the '\\n' (or the first non-digit character the user typed). ,期望这将等待按键,它不会 - 它只会读取'\\n' (或用户键入的第一个非数字字符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM