【问题标题】:How do I get the size of a c-string input in cin?如何在 cin 中获取 c 字符串输入的大小?
【发布时间】:2022-08-06 21:24:49
【问题描述】:

所以,基本上我想用 c++ 编写一个程序,通过将字符移动 ascii 表中的随机数来加密文本。但首先我需要用户获取一个字符串。当我想将 c 字符串存储在 char 数组中时,我的问题是我首先需要知道字符串的大小才能在数组中具有正确的大小。我怎样才能在不知道未来的情况下得到它? 提前致谢!

标签: c++ arrays c-strings cin


【解决方案1】:

以下是解决您遇到的这个问题的两种简单方法。
您可以根据程序的需要选择其中之一。

这里:

#include <iostream>
#include <string>

#define METHOD_NUM 1 // set this to 1 for the 1st approach
                     // or 2 for the 2nd approach

int main( )
{
    // an arbitrary size, I chose 20 for demo
    constexpr std::size_t requiredCharsCount { 20 };

#if METHOD_NUM == 1

    std::string user_input { };
    std::size_t buffSize { };

    do
    {
        std::getline( std::cin, user_input );

        // number of chars in the user input
        buffSize = user_input.size( );

    } while ( buffSize > requiredCharsCount );

#else

    // + 1 is for the '\0' aka the null terminator
    constexpr std::size_t buffSize { requiredCharsCount + 1 };
    
    std::string user_input( buffSize, '\0' );
    std::cin.getline( user_input.data( ),
                      static_cast<std::streamsize>( user_input.size( ) ) );

#endif

    std::cout << "The user entered: " << user_input
              << '\n';

    // manipulate the string however you want
    // just make sure that the indices you're using are
    // less than buffSize to avoid buffer overrun
    user_input[0] = '1';
    user_input[5] = 'g';
    user_input[2] = '@';
}

首先,我建议您使用std::string 类,因为它会为您处理所有必要的分配/解除分配并自动跟踪这些内容。一个C 样式数组甚至std::array 也不会拥有这种开箱即用的奢侈品。

现在,第一种方法让用户输入任意数量的字符,然后程序检查输入的字符数以确保它不大于预定义的数字(即requiredCharsCount,我已将其设置为20)。如果是,那么程序将要求新的输入。如果您不想为用户设置限制,您可以删除该变量和 do-while 循环。

说到第二种方法,如您所见,它允许用户输入有限数量的字符(再次,20) 并且即使用户的字符串包含的内容超过限制,也不会读取超过限制。这种方法效率更高,但显然有我刚才提到的局限性。

【讨论】:

猜你喜欢
  • 2023-03-29
  • 2021-05-12
  • 2021-01-20
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
相关资源
最近更新 更多