21xrx.com
2025-06-19 01:16:01 Thursday
登录
文章检索 我的文章 写文章
C++读取输入的字符串
2023-07-01 02:44:42 深夜i     22     0
C++ read input string parsing

C++是一种广泛使用的编程语言,它支持各种数据类型,包括字符串。在C++中,读取输入的字符串有几种方法,我们来看一下。

使用getline函数读取字符串

在C++中,可以使用getline函数来读取一行输入,包括空格和制表符。以下是用getline函数读取字符串的示例代码:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str;
  cout << "Enter a string: ";
  getline(cin, str);
  cout << "You entered: " << str << endl;
  return 0;
}

在这个示例中,从标准输入设备读取一行输入,并将其存储在名为str的string变量中。

使用cin函数读取字符串

另一种常用的读取字符串的方法是使用cin函数。以下是用cin函数读取字符串的示例代码:

#include <iostream>
#include <string>
using namespace std;
int main()
  string str;
  cout << "Enter a string: ";
  cin >> str;
  cout << "You entered: " << str << endl;
  return 0;

与getline函数不同,cin只会读取到第一个空格或制表符为止,因此如果输入的字符串包含空格,则会把空格后面的部分截断。

使用get函数读取字符串

get函数是C++中用于读取字符的函数,我们可以使用它来逐个读取字符并构建字符串。以下是用get函数读取字符串的示例代码:

#include <iostream>
using namespace std;
int main()
{
  char c;
  string str;
  cout << "Enter a string: ";
  while(cin.get(c) && c != '\n')
  {
    str += c;
  }
  cout << "You entered: " << str << endl;
  return 0;
}

在这个示例中,我们使用一个while循环来读取每个字符,并将其添加到名为str的字符串变量中,直到遇到换行符为止。

总结

以上是几种使用C++读取输入的字符串的方法,getline函数可以读取整行输入,包括空格和制表符。cin函数只会读取到第一个空格或制表符为止,而get函数则可以逐个读取字符并构建字符串。选择哪种方法取决于输入所包含的数据,以及处理这些数据的目的。

  
  

评论区