C++读取字符串方式汇总
在C++中,读取字符串的方法主要有以下几种:
使用 cin:
cin
是C++中最基础的输入方法,常与 >>
操作符一起使用。 ## 示例代码: #include <iostream>
using namespace std;
int main() {
string str;
cin >> str; // 读取一个字符串,直到遇到空格
cout << str;
return 0;
}
使用 getline() 函数:
getline()
函数用于读取一行字符串,直到遇到换行符。
它可以从 cin
或其他输入流中读取。 ## 示例代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
getline(cin, str); // 读取一行字符串
cout << str;
return 0;
}
使用 stringstream 类:
stringstream
类可以从字符串中读取数据,类似于从文件或标准输入中读取。 ## 示例代码:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string str = "example string";
stringstream ss(str);
string word;
while (ss >> word) { // 从stringstream读取单词
cout << word << endl;
}
return 0;
}
使用文件输入流 (ifstream):
如果字符串来自文件,可以使用 ifstream
读取。 ##
示例代码: #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("example.txt");
string str;
while (getline(file, str)) { // 从文件中逐行读取
cout << str << endl;
}
file.close();
return 0;
}
这些方法可以根据具体需求和上下文来选择使用。例如,当你需要读取含空格的整行字符串时,getline()
是更好的选择,而 cin
更适合于分段读取或读取单个词汇。