使用std::getline()读取一行
Using std::getline() to read a single line?
我的目标是提示用户输入消息/句子,然后使用getline()
在屏幕上打印出来。以下是我尝试过的两种不同的尝试。
第一次尝试:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
chat message[80];
cout << "n what is your message today?" << endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != ' '; ++i)
cout << message[i] << ' ';
cout << endl;
}
}
第二次尝试:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
string a = "a string";
cout << "n what is your message today?" << endl;
while(getline(cin,a))
cout << a;
cout<<endl
}
}
对于第一次尝试,代码只需打印出"你今天的消息是什么?"然后退出。我根本没有机会输入任何字符串。第二次尝试时,它一直要求我输入消息。每次,当我用"\n"输入内容时,它都会在屏幕上显示我输入的内容。我使用control+c来中断正在运行的进程,使其停止。
编辑:为了澄清和解释我的观点,我从一个较长的代码中提取了第一次尝试,如下所示。
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
char header[] = "n *** C Strings ***nn"; // define a c string
int main()
{
char hello[30] = "Hello ", name[20], message[80]; // define a c string hello, declare two other c strings name and message
string a="fivelength";
cout << header << "Your first name: ";
cin >> setw(20) >> name; // Enter a word.
strcat( hello, name); // Append the name.
cout << hello << endl;
cin.sync(); // No previous input.
cout << "nWhat is the message for today?"
<< endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != ' '; ++i)
cout << message[i] << ' ';
cout << endl;
}
return 0;
}
对于上面的代码,我没有机会在屏幕上输入消息。我将把它作为另一个问题。
如果这太复杂了,可以简单地使用std::string
,这是事实上的C++字符串,并调用该方法,而不使用循环。
您不需要循环,因为不是要重复读取行,而是只想读取一行,所以不需要循环。
#include <iostream>
#include <string> // not cstring, which is the C string library
using namespace std;
int main(void)
{
string message; // it can be an empty string, no need to initialize it
cout << "What is your message today?" << endl;
getline(cin, message);
cout << message;
cout<<endl;
return 0;
}
输出(输入:"Hello Stack Overflow!"(:
What is your message today?
Message: Hello Stack Overflow!
PS:正如@fredRalson所评论的,如果在第一个示例中将chat
更改为char
,它应该会起作用。然而,该代码与C.有很多共同点
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 而(!inputfile.eof())只读取第一行?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 需要从存档中读取一行文本.txt直到找到"hhh",然后转到下一行
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 从文件中的一行读取特定数据-C++
- 使用std::getline()读取一行
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 从文件读取并在一行中写入 cout
- 将 ifstream 文件和每一行读取到数组中
- 从文件 c++ 中的下一行读取
- 在同一行读取具有多个类型的文件
- 写入终端并从同一行读取
- 如何在c++中从最后一行读取文本文件
- 逐行读取数组,每一行读取3个值
- 在同一行读取字符串和整数
- 从一行读取hh:mm格式的时间