Moe*_*oeb 17 c++ string io stl
#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
Run Code Online (Sandbox Code Playgroud)
同样,我如何写出instdout或文件?
Yac*_*oby 28
您正在尝试将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;
Run Code Online (Sandbox Code Playgroud)
但是当读取字符串时,std :: cin会在遇到空格或新行时立即停止读取.您可能希望使用getline从控制台获取整行输入.
std::getline(std::cin, in);
Run Code Online (Sandbox Code Playgroud)
您对文件使用相同的方法(处理非二进制数据时).
std::ofstream ofs('myfile.txt');
ofs << myString;
Run Code Online (Sandbox Code Playgroud)
有很多方法可以将文本从 stdin 读取到std::string. 但 s的问题std::string是它们会根据需要而增长,这反过来意味着它们会重新分配。a 在内部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));
Run Code Online (Sandbox Code Playgroud)
上述所有内容将复制在标准输入中找到的所有文本,直到文件结尾。如果您只想要一行,请使用std::getline():
#include <string>
#include <iostream>
// ...
string in;
while( getline(cin, in) ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
如果您想要单个字符,请使用std::istream::get():
#include <iostream>
// ...
char ch;
while( cin.get(ch) ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30741 次 |
| 最近记录: |