c++ - 向用户询问指定数量的字符?

标签 c++

我是 C++ 的新手,我想提示用户准确输入 10 个字符,更多的字符将被忽略,例如:

  • 请输入 10 个字符:

123412341234

  • 您输入的是:1234123412

//而34会被忽略,因为他们输入的多于10

我现在到了这里:

string userInput;

    cout << "Please enter 10 characters!\n";
    cin >> userInput;

    cout << "You entered: "<< userInput << endl;

谢谢大家。希望我尽可能准确。

最佳答案

只要求用户输入一个字符串,然后取其子串

std::string userInput;

std::cout << "Please enter 10 characters: ";
std::cin >> userInput;

if(userInput.length() > 10)
{
    userInput = userInput.substr(0, 10);
}

std::cout << "You entered: " << userInput << std::endl; 

关于c++ - 向用户询问指定数量的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53254476/

相关文章:

c++ - 如何读取 C++ 中系统调用失败时显示的失败日志消息?

c++ - 为什么在 C 程序中从 main() 返回 0?

c++ - 在 OpenGL 中渲染火焰

c++ - 如何通过继承管理运算符重载

c++ - ffmpeg:如何用 sws_scale() 替换 img_convert()

c++ - 为什么所有像素值的锁定位都返回 -842150451?

c++ - 在 Visual Studio 2013 中构建 OpenSSL

c++ - Recv方法使用

c++ - 当brew安装opencv3时,我得到警告,该公式没有--with-contrib选项

c++ - 如何配置 Makefile 以使用 OpenCV