I am confused as to how to take multiple strings that have numbers in them and convert them into an int. I have multiple lines of strings that are stored in data into ints and then insert them into a 2 dimensional arrays called values. A similar question was posted earlier on StackOverflow; however it does not seem to be working for me. I printed out what each line in data is, each string in data is as follows.
75
95 64
17 42 82
18 35 87 10
However when I output the numbers from value by using two for loops in main, it outputs as this.
75
0
0
0
95
64
0
0
95
64
0
0
17
42
82
0
17
42
82
0
18
35
87
10
18
35
87
10
0
0
0
0
I found that there are 8 columns and 8 elements in the array values when I printed the sizeof(values) and sizeof(values[0]); however, it appears that the program terminated as the last print statement, where I print hello does not occur. I provided the code I'm using below. I would like to know why this is occurring
and how I can fix it? Thanks.
//const char DELIMITER = ' ';
int **values, // This is your 2D array of values, read from the file.
**sums; // This is your 2D array of partial sums, used in DP.
int num_rows; // num_rows tells you how many rows the 2D array has.
// The first row has 1 column, the second row has 2 columns, and
// so on...
bool load_values_from_file(const string &filename) {
ifstream input_file(filename.c_str());
if (!input_file) {
cerr << "Error: Cannot open file '" << filename << "'." << endl;
return false;
}
input_file.exceptions(ifstream::badbit);
string line;
vector<string> data;
try {
while (getline(input_file, line)) {
data.push_back(line);
num_rows ++;
}
input_file.close();
} catch (const ifstream::failure &f) {
cerr << "Error: An I/O error occurred reading '" << filename << "'.";
return false;
}
for(int x = 0; x < data.size(); x++){
cout << data[x] << endl;
}
//https://stackoverflow.com/questions/1321137/convert-string-containing-several-numbers-into-integers
//Help on making multiple numbers in a string into seperate ints
values = new int*[num_rows];
vector<int> v;
for(int y = 0; y < data.size(); y++){
istringstream stream(data[y]);
values[y] = new int[y + 1];
int z = 0;
while(1) {
int n;
stream >> n;
if(!stream)
break;
values[y][z] = n;
z++;
}
z = 0;
}
sums = values;
return true;
}
int main(int argc, char * const argv[]) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <filename>" << endl;
return 1;
}
string filename(argv[1]);
if (!load_values_from_file(filename)) {
return 1;
}
cout << sizeof(values) << endl;
cout << sizeof(values[0]) << endl;
for(int x = 0; x < sizeof(values); x++){
for(int y = 0; y < sizeof(values[x]); y++){
cout << values[x][y] << endl;
}
cout << endl;
}
cout << "hello" << endl;
return 0;
}
See this :
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string str;
ifstream fs("D:\\Myfolder\\try.txt", ios::in);
stringstream ss;
std::string item;
if (fs.is_open())
{
ss << fs.rdbuf();
str = ss.str();
cout << str << endl;
fs.close();
}
cout << "\n\n Output \n\n";
while (std::getline(ss, item, ' '))
{
cout << std::atoi(item.c_str()) <<" ";
}
return 0;
}
Related
I was stuck in this problem, I tried to read the datas from my csv file.
I will put my output and source code below.
As you can see,I'm printing the value of tmp[i] first and then I use another array to store the value in column tmp[i].
But the outputs are wrong. It's value should be the same as tmp[i].
Hoping someone can help me deal with this.
output:
69
26
54
3
69
54.1442
54.6054
54.1772
double stockp1[1000];
double stockp2[1000];
double stockp3[1000];
double stockp4[1000];
int c=0,d=0,e=0,f=0;
while (getline(inFile, line))
{
vector<string> a = _csv(line);
stockp1[c++] = atof(a[tmp[0]].c_str());
stockp2[d++] = atof(a[tmp[1]].c_str());
stockp3[f++] = atof(a[tmp[2]].c_str());
stockp4[e++] = atof(a[tmp[3]].c_str());
}
for (int i = 0; i < 4; i++)
{
cout << tmp[i] << endl;
}
cout << stockp1[0] << endl;
cout << stockp2[0] << endl;
cout << stockp3[0] << endl;
cout << stockp4[0] << endl;
}
vector<string> _csv(string s)
{
vector<string> arr;
istringstream delim(s);
string token;
int c = 0;
while (getline(delim, token, ','))
{
arr.push_back(token);
c++;
}
return arr;
}
So I have a program that reads in a certain number of keys. An example would be
5 1 10 21 9 6 21 11 13 16 20
The text file example would be
Java 2 linux 3 fear 0 pool 2 do 0 red 1 lock. 1 I 0 random 2
I want my program to start at Java and depending on first key, which in this case is 5, would move over 5 elements leading to "red". And so on and so on. However, I have managed to read in all the data and put them into arrays, I am just having trouble figuring out how to move the pointer in the array.
Code:
#include <iostream>
#include <fstream>
using namespace std;
struct pieces {
char word[5];
int jump;
} ;
// Main Function
int main ()
{
// declare variables
int wordCount[2];
int keyCount[2];
int numKeys, numKeys2;
int numWords;
int keyAmount = 1;
int wordAmount = 23;
int keyarr[11];
pieces cypher[wordAmount];
char filename[10];
ifstream inData;
int temp[10];
//prompt user for input file
cout << " Enter file name: ";
cin >> filename;
inData.open(filename);
if(inData.is_open());
{
// read in data
for ( numKeys = numWords = 0; numKeys < keyAmount; numKeys++){
// read in num of words and keys
inData >> wordCount[numKeys] >> keyCount[numKeys];
//read in words followed by jump key
for( numWords = 0; numWords < wordAmount; numWords++){
inData >> cypher[numWords].word >> cypher[numWords].jump;
}
// read in the actual keys
for( numKeys2 = 0; numKeys2 < wordCount[numKeys]; numKeys2++){
inData >> keyarr[numKeys2];
}
}
//print out data
for( int j = 0; j < numKeys; j++){
cout << wordCount[j] << "\n";
cout << keyCount[j] << "\n";
}
cout << "\n";
for ( int i = 0; i < wordAmount; ++i){
cout << cypher[i].word << " ";
cout << cypher[i].jump << " ";
}
cout << "\nKeys: " << "\n";
for(int k = 0; k < 11; k++){
cout << keyarr[k] << " ";
}
cout << "\n";
}
inData.close();
return 0;
}
I wanted to break the loop when the user doesn't want to add anymore:
#include<iostream>
using namespace std;
int main() {
int i = 0, a = 0, h = 0;
cout << "Enter numbers to be added:\n ";
for(i=0; ??; i++) {
cout << "\n" << h << " + ";
cin >> a;
h = h+a;
}
return 0;
}
Use std::getline to read an input line and exit the loop when the line is empty.
#include<iostream>
#include <sstream>
int main() {
int a = 0, h = 0;
std::cout << "Enter numbers to be added:\n ";
std::string line;
std::cout << "\n" << h << " + ";
while (std::getline(std::cin, line) && // input is good
line.length() > 0) // line not empty
{
std::stringstream linestr(line);
while (linestr >> a)// recommend better checking here. Look up std::strtol
{
h = h+a;
std::cout << "\n" << h << " + ";
}
}
return 0;
}
And output:
Enter numbers to be added:
0 + 1 2 3 4 5 6 7 8 9
1 +
3 +
6 +
10 +
15 +
21 +
28 +
36 +
45 +
Note that this allows multiple entries per line and looks pretty ugly, so OP is probably more interested in:
#include<iostream>
int main() {
long a = 0, h = 0;
std::cout << "Enter numbers to be added:\n ";
std::string line;
std::cout << "\n" << h << " + ";
while (std::getline(std::cin, line) && // input is good
line.length() > 0) // line not empty
{
char * endp; // will be updated with the character in line that wasn't a digit
a = std::strtol(line.c_str(), &endp, 10);
if (*endp == '\0') // if last character inspected was the end of the string
// warning: Does not catch ridiculously large numbers
{
h = h+a;
}
else
{
std::cout << "Very funny, wise guy. Try again." << std::endl;
}
std::cout << "\n" << h << " + ";
}
return 0;
}
Output
Enter numbers to be added:
0 + 1
1 + 1 2 3 4
Very funny, wise guy. Try again.
1 + 2
3 + 44444
44447 + jsdf;jasdklfjasdklf
Very funny, wise guy. Try again.
44447 + 9999999999999999999999
-2147439202 +
It is easier to use a sentinel value that you can check against, something like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int sum = 0;
string userInput;
while(true)
{
cout<<"Enter number to be added ('q' to quit): ";
cin >> userInput;
if( (userInput == "q") || (userInput == "Q") )
{
break;
}
try
{
sum += stoi( userInput );
}
catch( const std::invalid_argument& e )
{
cerr << "Invalid input \"" << userInput << "\" received!" << endl;
return EXIT_FAILURE;
}
}
cout << "Sum: " << sum << endl;
return EXIT_SUCCESS;
}
std::getline(std::istream&, std::string&) happily gives all lines including empty lines:
#include <iostream>
#include <string>
int main() {
long long accumulator = 0;
while (true) {
// read a (possibly empty) line:
std::string buf;
if (!std::getline(std::cin, buf)) {
std::cerr << "The input stream is broken." << std::endl;
break;
}
// was the entered line empty?
if (buf.empty()) {
std::cerr << "You entered a blank line" << std::endl;
break;
}
// convert string to integer
std::size_t pos;
long long summand;
try {
summand = std::stoll(buf, &pos, 10);
} catch (std::invalid_argument &) {
std::cerr << "Not an integer: " << buf << std::endl;
continue;
} catch (std::out_of_range &) {
std::cerr << "Out of range: " << buf << std::endl;
continue;
}
if (pos != buf.size()) {
std::cerr << "Not an integer on its own: " << buf << std::endl;
continue;
}
// do something with the data:
accumulator += summand;
}
std::cout << "accumulator = " << accumulator << std::endl;
return 0;
}
I have a char array (lets' say "13 314 43 12") and i want to put the first number (13) into a separate integer . how do i do that ? is there any way like splitting the first number into 10 + 3 and then adding them to the int ?
I am not sure what you mean by getting 1 and 3, but if you want to split the space-separated string into integers I suggest using a stream.
std::istringstream iss(s);
int n;
while(iss >> n)
{
std::cout << "Integer: " << n << std::endl;
}
[edit] Alternatively, you could parse the string yourself, something like this:
char* input = "13 314 43 12";
char* c = input;
int n = 0;
for( char* c = input; *c != 0; ++c )
{
if( *c == ' ')
{
std::cout << "Integer: " << n << std::endl;
n = 0;
continue;
}
n *= 10;
n += c[0] - '0';
}
std::cout << "Integer: " << n << std::endl;
#include <cstring>
#include <iostream>
#include <stdlib.h>
int main ()
{
char str[] = "13 45 46 96";
char * pch = strtok (str," ");
while (pch != NULL)
{
std::cout << atoi(pch) << "\n"; // or int smth=atoi(pch)
pch = strtok (NULL, " ");
}
return 0;
}
If you just want the first number, just use a function like atoi() or strtol(). They extract a number until it runs into the null terminated character or a non-numeric number.
According to your question I think following code will give some idea.
#include <string>
#include <iostream>
using namespace std;
int main(){
char s[] = "13 314 43 12";
//print first interger
int v = atoi(s);
cout << v << std::endl;
//print all integer
for (char c : s){
if (c == ' ' || c == '\0'){
}else{
int i = c - '0';
cout << i << std::endl; // here 13 print as 1 and 3
}
}
}
If you want to print first number you can use
int v = atoi(s);
cout << v << std::endl;
If you want to split and print all integers Ex: 13 as 1,3
for (char c : s){
if (c == ' ' || c == '\0'){
}else{
int i = c - '0';
cout << i << std::endl; // here 13 print as 1 and 3
}
}
Question: why does it print out the correct values inside the while loop (while reading / inputting the file) but not outside the while loop? I don't understand.
Thank you very much for any help.
input file:
1
2
3
4
5
#include <iostream>
#include <string>
#include <fstream>
#include <string>
using namespace std;
int sumNumbers(int sum, int* numbers, int numElements, int count)
{
if (count == numElements) return sum;
sumNumbers(sum + numbers[count], numbers, numElements, count + 1);
return 0;
}
int main(int argc, char* argv[])
{
int* numbers;
int numElements = 0;;
int sum = 0;
string fileName = argv[2];
ifstream ifile(fileName);
if( ifile.fail() ) {
cout << "The file could not be opened. The program is terminated." << endl;
return 0;
}
while ( !ifile.eof() ) {
numbers = new int[++numElements];
ifile >> numbers[numElements - 1];
cout << "Position " << numElements - 1 << ": " << numbers[numElements - 1] << endl;
}
cout << numbers[0] << endl;
cout << numbers[1] << endl;
cout << numbers[2] << endl;
cout << numbers[3] << endl;
cout << numbers[4] << endl;
cout << "--------------\n";
for(int i = 0; i < numElements; i++) {
cout << "Position " << i << ": " << numbers[i] << endl;
}
sumNumbers(sum, numbers, numElements, 0);
cout << "The sum of the numbers in the file is: " << sum << endl;
return 0;
}
output:
Position 0: 1
Position 1: 2
Position 2: 3
Position 3: 4
Position 4: 5
0
-805306368
0
-805306368
5
--------------
Position 0: 0
Position 1: -805306368
Position 2: 0
Position 3: -805306368
Position 4: 5
The sum of the numbers in the file is: 0
You are instantiating (and leaking) a new array in each loop iteration. And you only fill one element of that array. After the loop ends, you are left with the final array, with only the last element set.
There are many questions on SO that deal with the problem of reading numbers from a file into an array or container. Here, numbers are read into an std::vector.
#include <fstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<int> numbers;
ifstream ifile(fileName);
std::istream_iterator<int> eof;
std::istream_iterator<int> it(ifile);
std::copy(it, eof, std::back_inserter(numbers));
for(int i = 0; i < numbers.size(); ++i)
{
cout << "Position " << i << ": " << numbers[i] << endl;
}
}
Alternatively, you can replace the istream_iterators and the call to std::copy by a while loop:
int n=0;
while (ifile >> n) {
numbers.push_back(n);
}
This part:
while ( !ifile.eof() ) {
numbers = new int[++numElements];
// ...
repeatedly allocates memory for numbers. At each new, previous values are lost, and the memory from the previous allocation is leaking. You can print the value correctly before the next call to new so it seems to work within the loop.
It is better to use a vector:
int new_number;
while ( ifile >> new_number) {
numbers.push_back(new_number);
// ...
and don't use file.eof() in the while condition.