How to input n lines in a string array? [duplicate] - c++

This question already exists:
Why does the program not stop for the input? [duplicate]
Closed 7 years ago.
I have to input an int n, and read n lines in a string array. But when I test my code, for example, I put 3, it will read only 2. I found that I should use vectors, but why, is there any way easier than vectors to read n lines ?
Example code:
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
string niz[n];
for (int t1 = 0; t1 < n; t1++) {
getline(cin, niz[t1]); }
for (int t2 = 0; t2 < n; t2++) {
cout << niz[t2] << endl; }
}

The problem is that when you read the number of lines the newline is still left in the stream, so the first line that is read is just an empty line (what remains after the number that you input).
See and example exchange of input and output when I modify the program a little to prefix each line of output:
C:\so-test>test
3
Mary had
A little lamb.
line [0]:
line [1]: Mary had
line [2]: A little lamb.
For the moment, I'll leave the solution as an exercise for the reader.

In the first for loop, first iteration takes what's left in that row after you input n. You can just put cin.ignore(); before the first for loop to ignore the rest of that line. It should work now.

Related

C++ Check String Array for Spaces/Returns

I would like to make a space/return check for a string array. And a bit more I guess...
The user enters two lines, both being strings. To accommodate for these two lines, rather than making two separate string variables, I made a string array called string x[2]. Then the input gets combined into one variable called string combined and then outputs everything on one line.
Anyways, I would like the program to allow each line to have multiple strings, i.e. line one is I like tuna and line two is blah blah. I tried to make this a multidimensional array like x[2][3] but then if they enter only one word in a line then this forces them to enter in more lines until the array is completely filled up.
I want the user to enter up to 3 words in each line and a maximum of two lines. So doesn't that mean I have to check for spaces and returns? If so, how?
I don't want to make this post codeless, so for some point of reference, here is my original code which only lets them enter one word per line and two lines:
int main()
{
string x[2], combined;
for (int i = 0; i < 2; ++i)
{
cin >> x[i];
if (i == 0) combined = x[0];
else
combined += " " + x[i];
}
cout << combined << endl;
}
/*
Program:
Hello
World
Hello World
Press any key to continue...
I apologize if this post/question is very ambiguous and seems like I haven't put much thought in, but I'm a beginner and haven't been able to figure this one out. Thanks for your time!
Use getline
for (int i = 0; i < 2; ++i)
{
getline(cin, x[i]);
}
Use getline to read entire line of input
string x[2];
cout<<"input first string"<<endl;
getline(cin, x[0]);
cout<<"input second string"<<endl;
getline(cin, x[1]);
cout<<"Printing first string "<<x[0]<<endl;
cout<<"Printing second string "<<x[1]<<endl;
there is one similar problem in C. there you can't use scanf() if user inputs the string with spaces (cause there will be an error), you have to use gets(), which is unsafe.

Reading Input Error

I am working on NOV14 on COdechef contest problems. and i stuck at this problem.
http://www.codechef.com/NOV14/problems/RBTREE
My algorithm working well, but i cant take the input correctly. the problem is i don't know how many number of inputs are given. but i need to store in multiple variables.
Take a look at here..
5
Qb 4 5
Qr 4 5
Qi
Qb 4 5
Qr 4 5
where 5 is the number of test cases,
can i read every test cases into variables.
if i take First test case I can take Qb to one variable, 4 to other and 5 to another.
But the problem is How to read a line which start with Qi.
Well, first of all, if you write C++, you should use C++ streams. Here's the code for input (which you can adjust for your own needs):
#include <iostream>
#include <fstream>
int main() {
std::ifstream file;
file.open("data.in");
int lines = 0;
file >> lines;
std::string query_type;
for (int i = 0; i < lines; i++) {
file >> query_type;
if (query_type == "Qi") {
std::cout << query_type << std::endl;
} else {
int x = 0;
int y = 0;
file >> x >> y;
std::cout << query_type << " " << x << " " << y << std::endl;
}
}
file.close();
return 0;
}
You'll need to check what you've read at each step, and then determine whether or not you need to read the numbers in.
So read two characters, and if the characters you've read are "Q" and "i", you don't need to read any numbers, and you can just step on to the next line. Otherwise, you should read the two numbers before going to the next line.

Importing data into array in C++

I have a school assignment that I feel should be relatively simply, but I've spent like 5 hours on this part now and can't figure out what I need to do. I'm trying to import 3 integers from each line in a file into 3 different arrays. Each line has an ID number, store number, and quantity ordered. I want to store them in 3 arrays, where the same index would address the integers taken from the same line in the text file.
Recommendations I'm getting from various other places say to use stringstream or a vector, neither of which I have used before and I assume are not needed at this point in the class. My code currently is:
bool loadArrays(const char* fileName, long idArray[], int storeArray[], int qtyArray[], int &count, int maxCells)
{
count = 0;
ifstream fileIn;
fileIn.open("data.txt");
int x = 0;
while ((fileIn.get()) && (x < maxCells))
{
fileIn >> idArray[x] >> storeArray[x] >> qtyArray[x];
count++;
x++;
std::cout << idArray[x] << endl;
}
fileIn.close();
return true;
}
It loops through fine. I'm passing the count variable by reference and printing it out after I run this function it gives me 20. However the cout << idArray[x] line above just displays 0 each time like I'm not importing data correctly?
I'm probably importing the data wrong, which is fine for now, but even so shouldn't I get at least SOMETHING in idArray[0]? The first line of data.txt is '16724 27 134' so idArray[0] should = 16724, yes? I thought the >> will import integers until it meets whitespace, so the numbers being spaced apart like above means that line should go into 3 arrays per line right?
I should point out I'm taking this course online for now to see how I like programming and my teacher effectively doesn't speak english so I'm kind of on my own learning this for now.
You're reading into position x of your array, and printing out position x + 1 (x++ between those lines), which obviously is still empty.
Try to print before incrementing x, like so:
fileIn >> idArray[x] >> storeArray[x] >> qtyArray[x];
std::cout << idArray[x] << endl;
count++;
x++;
You're calling fileIn.get() without using its return value. The get() method extracts on character from the stream and returns it, it doesn't check whether there's still a character in the stream.
You should put the actual input operation inside the loop parameters as it is a much better way of checking if the stream performed a successful read:
while ((fileIn >> idArray[x] >> storeArray[x] >> qtyArray[x]) && (x < maxCells))
Also, as pointed out in the comments, you're incrementing x before printing idArray[x], so it will skip the first index. Put x++ after the insertion.

loop not correctly operated

This is my code here i am trying to find the biggest length of same length characters at a time like "a a a bb bb bc sa sa a a" so answer is 5 for two characters at a time for 5 times adjacently .
this is my code , my question is that when i am trying to take the input , for my first input it is not going to getline but printf in last lines and then it takes a line and prints output
like if i give
5 it writes 1 then it takes getline , but i want it to take getline first rather than printf, in this way for my 5 input it prints 1 and 4 desired outputs .i want 5 desired can you tell me why..
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
int main()
{
int a,j;
scanf("%d",&a);
for(j=0;j<a;j++)
{
vector<int> v;
string s;
getline(cin,s);
int i,cnt =0;
for(i=0;i<s.length();i++)
{
if(s[i] != ' ')
{
cnt++;
}
else
{
v.push_back(cnt);
cnt =0;
}
}
v.push_back(cnt);
int k=0;
int ps =0;
int sp=0;
while(k<v.size()-1)
{
if (v[k+1] - v[k] == 0)
{
sp++;
k++;
}
else
if (sp >= ps)
{
ps = sp;
k++;
sp=0;
}
else
{
k++;
sp=0;
}
}
if (sp<ps)
printf("%d",ps+1);
else
printf("%d",sp+1);
}
return 0;
}
You shouldn't be mixing scanf with getline, try to only use one or the other (and getline is a better option).
What is happening is that scanf stops parsing once it has finished reading an int. It does not consume the end of line character you type, or anything else you could have entered after that number. So getline picks up whatever was left on that first line (possibly just the newline char).
A "quick" but dirty fix would be to change your scanf call so that it swallows the whitespace after the int:
scanf("%d ",&a);
// ^ notice the space there
But that's not a real fix. Use getline and a string stream (in <sstream>) to get the first number, and your code will work as you intend it to. You'll find examples of using the istringstream to extract a number in this FAQ: How to convert a number to string and vice versa in C++
You might also be interested in this other question:
Split a string in C++?, the answers demonstrate ways to split a string that are less error-prone than what you're doing here.
How are you entering everything exactly? I think the problem may be that your getline() is reading your last [enter] off of the stream, thus automatically putting an empty string into s. That would result in the 1 you're getting. Try this for your scanf:
scanf("%d\n",&a)
That should absorb the [enter].

Read from stdin and store values into array C++ [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
How to convert a 2d char array to a 2d int array?
I'm trying to read input from stdin and stop reading when encountering EOF. I need to store these values as integers in a 2x2 array, array[i][j].
I'm reading in 81 Sudoku characters (integers) from a single line + 2 more characters (\n and EOF) for a total of 83.
Ex:
STDIN -- > 123414292142341......2\n <EOF>
How do I only store the numbers in each array[i][j]? and stop reading in when I encounter an <EOF> ?
So, after every 9 ints, I need to increment j to get the next row.
I'm looking to do this in C++
Thanks!
I have tried this so far
//Read in single line of 83 characters (81 sudoku integers + \n and
//Store each integer into array of corresponding row and column
#include iostream
using namespace std;
string input_line;
int main()
{
while(cin) {
getline(cin, input_line);
};
return 0;
}
How do I tokenize the string "input_line" into a character of integers? and then to atoi to convert to int, and then finally store them in the Sudoku array??
OK, thanks almost done. but I now keep getting an invalid conversion from 'char' to 'const char*' error!
#include <iostream>
#include <stdlib.h>
using namespace std;
string input_line;
int main()
{
char buffer[9][9];
int sudoku[9][9];
int v;
cout << "Enter input: " << endl;
cin >> (char*)buffer;
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
v = atoi(buffer[i][j]);
sudoku[i][j] = v;
If you want in C++ then you may choose to use C++ style cin. Following is pseudo code:
cout<<"Enter input:\n";
char sudoku[9][9];
cin>>&sudoku[0][0];
Here we are taking advantage of the fact that any digit will be less than < 256. So your table will be arranged inside the sudoku[][] automatically.