team! I have a task in which I have to read a string from the console from one line, from new line I have to read a row of integers. The integers represent the level of circuling rotation of the string. (abcd, 1 -> bcda) My ploblem comes in the main method while reading. Here it is:
int main(){
int k;
string s;
while(cin >> m){
while(cin >> k){
string temp = m;
shift(k);
cout << m << endl;
m = temp;
} }
I need to read multiple examples, but this code reads m(the string) only once and k(the level) is read by infinity. How can I make it read m, on the new line array of k-s and then m again?
Here is the whole program:
#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;
}
P.S. What is Segmentation fault??? And can this program cause it?
To read lines use getline. But getline only reads a string, so read your line of integers into a string and then use istreamstream to read to integers from the string. Something like this
while (getline(cin, m))
{
string int_line;
if (getline(cin, int_line))
{
istringstream int_input(int_line);
while (int_input >> k)
{
...
}
}
}
That may not be exactly what you need, I didn't understand exactly what you were trying to do. But the key points are to use the right tools for the job. You want to read lines so use getline, and you want to read numbers from the second line so use istringstream to read the numbers after you have read in the line.