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

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.

Related

How to convert string to an int array using stoi() && substr()

im triying to convert an string to an integer and save those numbers into an array, i tried like this
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
int number[5];
string input;
//numbers
cout << "type sonme numbers"<<endl;
cin >> input;
for(int i = 0 ; i<= 4; i++){
number[i] = stoi(input.substr(i,i),0,10);
cout << number[i];
}
return 0;
}
when i run it this error comes out:
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
Your first loop is asking for a substring beginning at index 0, with length 0, so you're passing an empty string to stoi. Even if you in fact provided valid inputs (a string of at least eight digits, so you could call .substr(4, 4) on it and get useful results), the first loop always tries to parse the empty string and dies. Don't do that.
It's unclear what the goal here is. If you meant to parse each digit independently, then what you wanted was:
number[i] = stoi(input.substr(i, 1), 0, 10);
which would parse out five sequential length one substrings.

Problem with forming string array using loop

I want to create a string array using loop inputs and then give ASCII based output for each character of the string.
Here is my code
int n;
cin >> n;
string arr[n];
for(int i=0;i<n;++i){
getline(cin,arr[i]);
}
for(int i = 0;i < n; ++i){
for(int j = 0;j < arr[i].length(); ++j){
cout << to_string(arr[i].at(j)) << " ";
}
cout << endl;
}
the program takes n : number of string inputs
but allows me to input only n-1 strings.
What is the problem here?
You are reading n strings, but the first one doesn't contain what you expect.
When you write input in the console, you write something like:
3\nstring1\nstring2
, where \n is the newline character (when you press Enter).
When you do cin >> n, you parse this input string, and you get the integer. Meaning that you remain with
\nstring1\nstring2
in the buffer. And when you do a getline, you parse everything up to the first newline (including the newline). That's why you get the first string empty.
A quick and dirty fix is to read the newline too:
int n;
char newline;
cin >> n >> newline;
, and then loop as you do now.
Some remarks about your code.
string arr[n] is not valid C++. In C++, there is no official support for arrays with variable size like this (some compilers support it, but this doesn't mean it's standard). You should use a std::vector:
std::vector<std::string> arr(n);
(the rest of the code remains the same). An even better way would be to declare it empty, and then use push_back to populate it.
Also, when comparing j < arr[i].length(), you are comparing a variable of type int with a variable of type size_t, which might be bigger than an int and create issues for very long strings. Use size_t as the type for j.
Use a std::vector
A vector is dynamic array. So change:
string arr[n];
to
std::vector<std::string> arr(n);
According to your code snippet what you want to read is a number of strings and then output for each of them the ASCII value of all of its characters:
If you have an input like the following
2
abc
def
you would like to obtains as a result something like the following:
97 98 99
100 101 102
In order to achieve that I see at least a couple of problems with your code.
C++ does not support variable size arrays by default. It means you cannot create an array whose size is not known at compile time (see this answer for more info about it)
In order to output the ASCII of the char you simply need to cast the char to int and that is it.
using getline in this case complicates the code because of the way getline works with newline. Simply use cin>>arr[i] to read each string.
Here is it a version of your code that does what you expect:
int n;
cin>>n;
vector<string> arr(n);
for(int i=0;i<n;++i)
cin>>arr[i];
for(const auto& s : arr){
for(const auto& c : s){
cout<<(int)c<<" ";
}
cout<<endl;
}
If you need a list of strings, you can use vector:
#include<vector>
#include<string>
int n;
cin >> n;
vector<string> arr(n);
for(int i = 0; i < n; ++i){
getline(cin, arr[i]);
}
for(auto& str : arr){
for(auto& c : str){
cout << to_string(c) << " ";
}
cout << endl;
}

Converting a C string to individual integers

This exercise asks to take a input as a character array of number then add up the digits of the number.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main() {
//Input a series of single digit numbers
char numbers[] = "a";
cout << "Input a series of single digit numbers." << endl;
cin >> numbers;
//convert the character array into a int array.
int sum = 0;
for (int i = 0; i < size; i++) {
sum += atoi(numbers[i]);
}
cout << "Sum of digits: " << sum;
return 0;
}
The atoi function, by my understanding, converts only whole character arrays (C strings) at a time, and I guess I cant step through the array, but it seems like this should work. My other option was to convert the Cstring to one large integer, then use the length of the string to step through and calculate the digits in each position but that's probably more inefficient that I could be making it.
What would you use to find single digits as ints for a character array?
char numbers[] = "a";
This creates an array of 2 char items. That's not sufficient for anything reasonable. Use a std::string instead.
cin >> numbers;
Better use std::getline from the <string> header.
sum += atoi(numbers[i]);
atoi takes a string as argument, not a single char. You want the sum of the digits, not the sum of the number values you get by applying atoi to all right substrings of the specification.
For a digit character ch, the corresponding digit value is ch - '0'.

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

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.

C++ file writing/reading

I'm trying to create an array, write array to the file and than display it. It seems to be working but i get just part of the output (first 3 elements) or i get values over boundaries.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int arr[20];
int i;
for (i = 0; i < 5; i++)
{
cout << "Enter the value to the array: " << endl;
cin >> arr[i];
}
ofstream fl("numbers.txt");
if (!fl)
{
cout << "file could not be open for writing ! " <<endl;
}
for (i = 0; i < arr[i]; i++)
{
fl<<arr[i]<<endl;
}
fl.close();
ifstream file("numbers.txt");
if(!file)
{
cout << "Error reading from file ! " << endl;
}
while (!file.eof())
{
std::string inp;
getline(file,inp);
cout << inp << endl;
}
file.close();
return 0;
}
The terminating condition in the for loop is incorrect:
for(i=0;i<arr[i];i++)
If the user enters the following 5 ints:
1 0 4 5 6
the for loop will terminate at the second int, the 0, as 1 < 0 (which is what i<arr[i] would equate to) is false. The code has the potential to access beyond the bounds of the array, for input:
10 11 12 13 14
the for loop will iterate beyond the first 5 elements and start processing unitialised values in the array arr as it has not been initialised:
int arr[20];
which could result in out of bounds access on the array if the elements in arr happen to always be greater than i.
A simple fix:
for(i=0;i<5;i++)
Other points:
always check the result of I/O operations to ensure variables contain valid values:
if (!(cin >> arr[i]))
{
// Failed to read an int.
break;
}
the for loop must store the number of ints read into the arr, so the remainder of the code only processes values provided by the user. An alternative to using an array, with a fixed size, and a variable to indicate the number of populated elements is to use a std::vector<int> that would contain only valid ints (and can be queried for its size() or iterated using iterators).
while (!file.eof()) is not correct as the end of file flag will set only once a read attempted to read beyond the end of the file. Check the result of I/O operations immediately:
while (std::getline(file, inp))
{
}
its like hmjd said
for(i=0;i<arr[i];i++)
looks wrong
it should look like this
int size;
size=sizeof(your array);
for(i=0;i<size;i++)
Try this:
//for(i=0;i<arr[i];i++)
for(i=0;i<5;i++)
[EDITED]
I would initialize the array with 0 like this: int arr[20] = {0}; In this case you can use for example:
while ((arr[i] != 0 || i < sizeof(arr))
i<array[i]
It is wrong beacuse it comapres with the content of the array ,it does not check the size of array .