【问题标题】:Why doesn't string class take in two words separated with space?为什么字符串类不接受用空格分隔的两个单词?
【发布时间】:2022-11-17 00:41:23
【问题描述】:

我想使用字符串对象获取人名。但是在我的代码中,如果我将两部分名称用空格分隔,则只显示第一部分。我的理解是 .c_str() 返回一个指向存储字符串的指针,终端为空。为什么空间有问题。我是 C++ 的新手,使用的是 Code::Blocks 13.12。这是我在我编写的另一个程序中遇到的问题的简化版本。 提前致谢。

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>


using namespace std;

int main()
{
   string sCusName;

   cout << "Please enter your name-> ";
   cin >> sCusName;


   int xsize = sCusName.length();
   char *tempBuffer = new char[xsize+1];

   strncpy(tempBuffer, sCusName.c_str(),xsize+1);

   cout << tempBuffer << " is a beautiful name." << endl;

   return 0;
}

当我输入单个零件名称时,程序运行正常。但是如果我输入用空格分隔的两部分名称。只收录了第一部分。

【问题讨论】:

    标签: string c-str


    【解决方案1】:

    使用cin 读取多字字符串是不可能的,而应该使用getline() getline() 函数有两个参数 cin 和字符串变量,例如:

       int main()
    {
       string sCusName;
    
       cout << "Please enter your name-> ";
       getline(cin,sCusName);
    
       cout << sCusName << " is a beautiful name." << endl;
    
       return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2019-12-02
      相关资源
      最近更新 更多