I/O 与嵌套而麻烦

I/O with nested while trouble

本文关键字:麻烦 嵌套      更新时间:2023-10-16

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 读取数字。