C++ 中输入字符串的方法:cin:从控制台读取字符串。getline(cin, string):读取一行字符串,直到遇到换行符。stringstream:将字符串作为流处理,可以读取和写入数据。ifstream:从文件中读取字符串。

C++ 中输入字符串的几种方法
在 C++ 中,输入字符串有以下几种方法:
1. cin
cin 是 C++ 中标准的输入流对象。它可以从控制台读取字符串,并将其存储在变量中。用法示例:
立即学习“C++免费学习笔记(深入)”;
<code class="cpp">#include <iostream>
using namespace std;
int main() {
string input;
cout << "Enter a string: ";
cin >> input;
cout << "You entered: " << input << endl;
return 0;
}</code>2. getline(cin, string)
getline(cin, string) 函数用于从控制台读取一行字符串,直到遇到换行符。用法示例:
<code class="cpp">#include <iostream>
using namespace std;
int main() {
string input;
cout << "Enter a string with spaces: ";
getline(cin, input);
cout << "You entered: " << input << endl;
return 0;
}</code>3. stringstream
stringstream 允许将字符串作为流来处理。它可以从字符串中读取和写入数据。用法示例:
<code class="cpp">#include <sstream>
using namespace std;
int main() {
string input = "Hello World!";
stringstream ss(input);
string word;
while (ss >> word) {
cout << word << " ";
}
return 0;
}</code>4. ifstream
ifstream 用于从文件中读取数据。它可以从文件中读取字符串,并将其存储在变量中。用法示例:
<code class="cpp">#include <fstream>
using namespace std;
int main() {
ifstream file("input.txt");
string input;
while (getline(file, input)) {
cout << input << endl;
}
file.close();
return 0;
}</code>以上就是c++++中输入字符串的几种方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号