【问题标题】:How to read and write a STL C++ string?如何读写 STL C++ 字符串?
【发布时间】:2011-02-06 16:49:05
【问题描述】:
#include<string>
...
string in;

//How do I store a string from stdin to in?
//
//gets(in) - 16 cannot convert `std::string' to `char*' for argument `1' to 
//char* gets (char*)' 
//
//scanf("%s",in) also gives some weird error

同样,我如何将in 写入标准输出或文件??

【问题讨论】:

    标签: c++ string stl io


    【解决方案1】:

    您正在尝试将 C 风格的 I/O 与 C++ 类型混合。使用 C++ 时,您应该使用 std::cinstd::cout 流进行控制台输入和输出。

    #include <string>
    #include <iostream>
    ...
    std::string in;
    std::string out("hello world");
    
    std::cin >> in;
    std::cout << out;
    

    但是在读取字符串时,std::cin 会在遇到空格或换行时立即停止读取。您可能想使用getline 从控制台获取整行输入。

    std::getline(std::cin, in);
    

    您对文件使用相同的方法(在处理非二进制数据时)。

    std::ofstream ofs("myfile.txt");
    
    ofs << myString;
    

    【讨论】:

      【解决方案2】:

      C++ 字符串必须使用 &gt;&gt;&lt;&lt; 运算符和其他 C++ 等效项来读取和写入。但是,如果您想像在 C 中一样使用 scanf,您始终可以以 C++ 方式读取字符串并使用 sscanf:

      std::string s;
      std::getline(cin, s);
      sscanf(s.c_str(), "%i%i%c", ...);
      

      输出字符串最简单的方法是:

      s = "string...";
      cout << s;
      

      但是 printf 也可以: [固定 printf]

      printf("%s", s.c_str());
      

      c_str() 方法返回一个指向以 null 结尾的 ASCII 字符串的指针,所有标准 C 函数都可以使用该指针。

      【讨论】:

      • 你使用printf是不安全的,应该是printf("%s", s.c_str());,防止缓冲区溢出。
      【解决方案3】:

      有很多方法可以将文本从标准输入读入std::string。不过,std::strings 的问题在于它们会根据需要增长,这反过来意味着它们会重新分配。在内部,std::string 有一个指向固定长度缓冲区的指针。当缓冲区已满并且您请求在其上添加一个或多个字符时,std::string 对象将创建一个新的、更大的缓冲区而不是旧缓冲区并将所有文本移动到新缓冲区。

      所有这一切都表明,如果您事先知道要阅读的文本长度,那么您可以通过避免这些重新分配来提高性能。

      #include <iostream>
      #include <string>
      #include <streambuf>
      using namespace std;
      
      // ...
          // if you don't know the length of string ahead of time:
          string in(istreambuf_iterator<char>(cin), istreambuf_iterator<char>());
      
          // if you do know the length of string:
          in.reserve(TEXT_LENGTH);
          in.assign(istreambuf_iterator<char>(cin), istreambuf_iterator<char>());
      
          // alternatively (include <algorithm> for this):
          copy(istreambuf_iterator<char>(cin), istreambuf_iterator<char>(),
               back_inserter(in));
      

      以上所有内容都将复制在标准输入中找到的所有文本,直到文件结束。如果您只想要一行,请使用std::getline()

      #include <string>
      #include <iostream>
      
      // ...
          string in;
          while( getline(cin, in) ) {
              // ...
          }
      

      如果您想要单个字符,请使用std::istream::get()

      #include <iostream>
      
      // ...
          char ch;
          while( cin.get(ch) ) {
              // ...
          }
      

      【讨论】:

        猜你喜欢
        • 2016-07-27
        • 1970-01-01
        • 1970-01-01
        • 2015-01-17
        • 1970-01-01
        • 2010-09-28
        • 1970-01-01
        • 1970-01-01
        • 2012-06-17
        相关资源
        最近更新 更多