[英]How do you input a string of a specific length?
Let's say I were to allow the user to input n
.假设我允许用户输入
n
。 They would then be able to input a string that must have n
characters.然后他们将能够输入一个必须包含
n
字符的字符串。 I don't want to use a loop because the string must be on one line.我不想使用循环,因为字符串必须在一行上。
Would there be a way to do this?有办法做到这一点吗?
This format is what I would prefer.这种格式是我更喜欢的。
int n;
cin >> n;
string test;
cin >> test[n];
Any help would be greatly appreciated:)任何帮助将不胜感激:)
You could truncate whatever they input to the first n many characters.您可以将他们输入的任何内容截断为前 n 个字符。
#include <string>
#include <iostream>
int n;
std::cin >> n;
std::string test;
std::cin >> test;
test = test.substring(0, n);
You could also test the validity of their input, and prompt them to re-enter it if they enter too many characters.您还可以测试他们输入的有效性,如果输入的字符过多,则提示他们重新输入。
int n;
std::cin >> n;
std::string test
do
{
std::cin >> test;
}
while(test.length() > n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.