如何从标准输入读取字符串直到遇到空行 [英] How to read string from stdin until meet blank lines
问题描述
考虑一个简单的程序.它必须从 stdin 获取字符串并保存到变量.没有说明输入多少行,但如果遇到换行符,程序必须终止.
Consider a simple program. It must take string from stdin and save to variable. It is not stated how many lines of input will be taken, but program must terminate if meet newline.
例如:标准输入:
abc
abs
aksn
sjja
\n
我试过了,但没有用.这是我的代码:
I tried but it doesn't work. Here is my code:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
// Constant
#define max 100000
struct chuoi
{
char word[10];
};
chuoi a[max];
void readStr()
{
int i=0;
while ( fgets(a[i].word, 10,stdin) != NULL)
{
if (a[i].word[0] == ' ') break;
a[i].word[strlen(a[i].word)-1] = '\0'; //replaced \n by \0
i++;
}
//length = i;
}
int main()
{
readStr();
return 0;
}
那么,如何解决这个问题?
So, how to solve this problem?
推荐答案
这里的另一种选择是使用 std::getline
来获取每一行.如果该行为空,或者输入失败,则退出循环.
One alternative here is to use std::getline
to get each line. If the line is empty, or the input fails, then exit the loop.
void readStr()
{
std::string str;
while ( std::getline(std::cin, str) && str.length() )
{
// use the string...
}
}
在示例代码中添加std::getline
和std::vector
的使用,并保持原始示例的精神;
Adding the std::getline
and use of std::vector
to your sample code, and keeping with the spirit of your original sample;
#include <string>
#include <iostream>
#include <vector>
const std::size_t Max = 100000;
struct chuoi
{
explicit chuoi(std::string const& str) : word(str)
{
}
std::string word;
};
void readStr(std::vector<chuoi>& a)
{
std::string str;
while ( std::getline(std::cin, str) && str.length() )
{
a.push_back(chuoi(str));
}
}
void writeStr(std::vector<chuoi> const& a)
{
for (auto i = a.begin(); i != a.end(); ++i) {
std::cout << i->word << std::endl;
}
}
int main()
{
std::vector<chuoi> a;
a.reserve(Max);
readStr(a);
writeStr(a);
return 0;
}
为了解决您眼前的问题,可以对代码进行最小的更改,如下所示;
To solve you immediate problem, minimal changes in the code can be made as follows;
void readStr()
{
int i = 0;
while ( fgets(a[i].word, 10, stdin) != NULL)
{
a[i].word[strlen(a[i].word) - 1] = '\0'; // transform the end of line character to NULL
if (strlen(a[i].word) == 0) {
break;
}
i++;
}
}
如果总是使用标准输入(stdin
),也可以使用gets
函数;
If the standard input will always be used (stdin
), the gets
function can also be used;
while ( gets(a[i].word) != NULL)
{
if (strlen(a[i].word) == 0) {
break;
}
i++;
}
注意事项;
fgets
读取直到stdin
上的enter"键,但包括换行符gets
也读取直到返回,但不包括换行符- 两个函数都为 NULL 终止输入
- 注意
gets
的形式,它不会检查缓冲区溢出情况
fgets
reads until the "enter" key on thestdin
but includes the new line charactergets
also reads until the return, but excludes the new line character- Both functions NULL terminate the input
- Be careful of the form of
gets
it does not check for buffer overflow conditions
这篇关于如何从标准输入读取字符串直到遇到空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!