I/O 与嵌套而麻烦
I/O with nested while trouble
team!我有一个任务,我必须从控制台从一行读取一个字符串,从新行我必须读取一行整数。整数表示字符串的循环旋转级别。(ABCD, 1 -> BCDA(我的 ploblem 在阅读时出现在主要方法中。在这里:
int main(){
int k;
string s;
while(cin >> m){
while(cin >> k){
string temp = m;
shift(k);
cout << m << endl;
m = temp;
} }
我需要读取多个示例,但是此代码仅读取m(字符串(一次,而k(级别(由无穷大读取。如何让它在 k-s 的新线性数组上读取 m,然后再次读取 m?
这是整个程序:
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
string m;
void reverse_arr(int a, int b)
{ unsigned i, j, k, c;
char tmp;
for (c=(b-a)/2, k=a, j=b, i=0; i<c; i++, j--, k++)
{ tmp = m[k];
m[k] = m[j];
m[j] = tmp;
}
}
void shift(unsigned k)
{
int N = m.length();
reverse_arr(0, k-1);
reverse_arr(k, N - 1);
reverse_arr(0, N - 1);
}
int main()
{
int k;
string s;
while(getline(cin,m)){
string int_line;
if(getline(cin,int_line)){
istringstream is(int_line);
while(is >> k){
string temp = m;
shift(k);
cout << m << endl;
m = temp;
}
}
}
return 0;
}
附言什么是分段故障???这个程序会导致它吗?
要读取行,请使用 getline。但是 getline 只读取一个字符串,因此将整数行读入字符串,然后使用 istreamstream 从字符串中读取整数。像这样的东西
while (getline(cin, m))
{
string int_line;
if (getline(cin, int_line))
{
istringstream int_input(int_line);
while (int_input >> k)
{
...
}
}
}
这可能不是你所需要的,我不明白你想做什么。但关键点是使用正确的工具来完成工作。您想读取行,因此使用 getline,并且您想从第二行读取数字,因此在读取行后使用 istringstream 读取数字。
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- I/O 与嵌套而麻烦
- 循环时嵌套的麻烦
- 在正确嵌套错误信息时遇到麻烦