2010-04-11 77 views
11
#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写出到标准输出或文件?如何读写STL C++字符串?

回答

21

您正试图将C风格的I/O与C++类型混合使用。当使用C++时,你应该使用std :: cin和std :: 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; 
0

C++串必须被读出和使用>><<运营商编写和其他C++当量。但是,如果你想使用scanf函数在C,可以随时读取字符串的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()指针返回到空叔方法所有标准C函数都可以使用ASCII字符串。

+2

你用printf是不安全的,应该'的printf(“%S “,s.c_str());'以防止缓冲区溢出。 – LiraNuna 2010-04-11 19:57:22

+0

你说得对,我会纠正它。 – 2010-04-11 21:55:20

3

有许多方法可以将stdin中的文本读入std::string。关于std::string的一点是,它们根据需要增长,这又意味着它们重新分配。内部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)) { 
     // ... 
    }