在 cpp 中使用 getline 输入数组中的空格分隔数字
Input Space Separated Numbers in arrays using getline in cpp
我一直在研究一个问题,在这个问题中,我需要在 CPP 的两个单独数组中获取空格分隔的输入(<=10),然后在下一行中获取其他一组空格分隔的输入。我为此在 cpp 中使用了 getline 函数。我面临的问题是接受输入的最后一行。我不知道我面临什么问题。当最后一行出现时,输出停止并等待我键入内容,然后它提供输出。这是我的代码。
while(test--)
{
int len[100];
int pos[100];
string a,b,code;
// int t=1;
cin>>code;
cin.ignore();//ignores the next cin and waits till a is not input
getline(cin,a);
// deque<char> code1;
// code1.assign(code.begin(),code.end());
int k=0;
int t=a.length();
for(int i=0;i<t/2+1;i++)//converts two n length arrays pos[] and len[]
{
scanf("%d",&len[i]);
while(a[k]==' ')
{
k++;
}
pos[i]=a[k]-48;
k++;
}
//int c;}
'
您的代码令人困惑,看起来应该不起作用。您正在使用带有cin/scanf的阻塞输入,因此如果标准输入上没有准备好输入,它会等待您是正常的。
这是您尝试执行的操作:
- 使用
getline
将行读入名为a
的字符串。 - 使用
scanf
将数据从a
读取到数组中。
但是,scanf
不是为此而生的。scanf
函数从键盘获取输入。我想你想使用 sscanf 输入字符串a
中的值。
但更好的是使用字符串流。
起初我以为你是在尝试从命令行读取输入的长度,所以我建议这样做:
size_t arr_len;
cin >> arr_len;
if (cin.fail())
{
cerr << "Input error getting length" << endl;
exit(1);
}
int* len = new int[arr_len];
int* pos = new int[arr_len];
for (int count = 0; count < arr_len; count++)
{
cin >> len[count];
if (cin.fail())
{
cerr << "Input error on value number " << count << " of len" << endl;
exit(1);
}
}
for (int count = 0; count < arr_len; count++)
{
cin >> pos[count];
if (cin.fail())
{
cerr << "Input error on value number " << count << " of pos" << endl;
exit(1);
}
}
delete [] pos;
delete [] len;
然后我看得更仔细了。看起来这就是您想要做的。我使用的是std::vector
而不是int[]
,但如果你真的想要,改变它并不难。
string line;
getline(cin, line);
if (cin.fail())
{
cout << "Failure reading first line" << endl;
exit(1);
}
istringstream iss;
iss.str(line);
vector<int> len;
size_t elements = 0;
while (!iss.eof())
{
int num;
iss >> num;
elements++;
if (iss.fail())
{
cerr << "Error reading element number " << elements << " in len array" << endl;
}
len.push_back(num);
}
getline(cin, line);
if (cin.fail())
{
cout << "Failure reading second line" << endl;
exit(1);
}
iss.clear();
iss.str(line);
vector<int> pos;
elements = 0;
while (!iss.eof())
{
int num;
iss >> num;
elements++;
if (iss.fail())
{
cerr << "Error reading element number " << elements << " in pos array" << endl;
}
pos.push_back(num);
}
相关文章:
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 野牛/yacc 解析器在不被空格分隔时跳过 grammer - "unexpected $end"
- 从 stdio 获取一行空格分隔的整数,而不知道它们是多少 (C++)
- 如何从文件中读取用空格分隔的数字
- 反转由空格分隔的字符串元素将返回比原始字符串更大的字符串
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 如果用户输入两个或多个由空格分隔的字符串C++如何防止缓冲区溢出?
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 非空格分隔的文本文件到 2D 矢量
- 如何在用空格分隔的行中获得无限的输入
- 如何从空格分隔的单个字符串中提取多个子字符串
- 如何获得一些用空格分隔的字符
- 在 cpp 中使用 getline 输入数组中的空格分隔数字
- C++ sscanf 空格分隔字符串
- 文本文件解析C++|用空格分隔
- 将空格分隔的输入读取到C++中的数组中