Sum all integers in a string C++ - c++

I have a C++ string in my code that is like:
"1 2 3 4 5 6 7 8"
I know the string is composed of integers separated by a space char. How can I sum them?
I'm quite a C++ newbie and in Java I'd simply do:
String str = "1 2 3 4 5 6 7 8";
int sum = 0;
for (int i = 0; i < str.split(" ").length; i++ {
sum += Integer.parse(str.split(" ")[i];
}
How can I do just like this with my string object in C++?
Some people suggested me stringstream but I still can't understand this object and I need to read the string entirely, getting every single digit within it.
Thanks in advance!
Update: some guys nicely tried to help me but still it's not working. Perhaps because of some quirk of my problem which I haven't clarified before. So here it goes:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
freopen("variable-exercise.in", "r", stdin);
int sum = 0, start = 0;
string line;
while(getline(cin ,line)) {
istringstream iss(line);
while(iss >> start) {
sum += start;
}
cout << start << endl;
sum = start = 0;
}
return 0;
}
Ah, the input file contains the following:
1
3 4
8 1 1
7 2 9 3
1 1 1 1 1
0 1 2 5 6 10
So, for each line, the program must print the sum of all integers in the string line. This example would generate:
1
7
10
21
5
24
thanks

Some people suggested me stringstream but I still can't understand this object and I need to read the string entirely
I guess you were given a good advice. With std::istringstream you could just read in values one after the other as you would read them from the standard input (or any other input stream).
For instance:
#include <sstream>
#include <string>
#include <iostream>
int main()
{
// Suppose at some time you have this string...
std::string s = "1 2 3 4 5 6 7 8 9 10";
// You can create an istringstream object from it...
std::istringstream iss(s);
int i = 0;
int sum = 0;
// And read all values one after the other...
while (iss >> i)
{
// ...of course updating the sum each time
sum += i;
}
std::cout << sum;
}

Like this:
std::stringstream s("1 2 3 4 5 6 7 8 9");
int n = 0;
int x;
while (s >> x)
n += x;
std::cout << n << std::endl;
After your edit:
cout << start << endl;
This is wrong, you should be printing sum instead:
cout << sum << endl;

I used C code to solve this problem. Here's the final solution:
#include <stdio.h>
#include <string.h>
int main() {
char *c;
char line[100];
int x, sum = 0;
while(gets(line)) {
for(c = strtok(line, " "); c ; c = strtok(NULL, " ")) {
sscanf(c, "%d", &x);
sum += x;
}
printf("%d\n", sum);
sum = 0;
}
return 0;
}
Hope it helps anyone who might have the same problem!

Related

How do divide txt file numbers into a positive number txt file and negative number txt file

#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
int masivs[24], x = 0, y = 0;
int negativi[20];
int pozitivi[20];
ifstream f;
f.open("f.txt");
while (f.good() && x < 24)
f >> masivs[x++];
f.close();
cout << masivs[1];
ofstream f2("f2.txt");
ofstream f1("f1.txt");
for (x = 0; x < 24; x++)
if (masivs[x] >= 0)
pozitivi[x] = masivs[x];
else
negativi[x] = masivs[x];
for (int k = 0; k < 8; k++)
{
f2 << negativi << endl;
}
for (int k = 0; k < 15; k++)
{
f1 << pozitivi << endl;
}
}
Ive been trying to find out how to do this for 2 days and im going crazy. Just please tell me how to do it. Im trying to divide the f.txt file numbers into f1.txt with the positives and f2.txt with the negatives. I have to read the f file with an array adn then write the positives in f1 and negatives in f2. and all the zeros in f3. Pls help ive been trying to find info on this but i cant do it.
the f.txt numbers:
-9
-8
-7
-6
-5
-4
-3
-2
-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
You have two major problems. One benign and one which leads to undefined behavior.
The benign problem is the statement
f2<<negativi<<endl;
This is exactly the same as
f2 << &negativi[0] << endl;
In other words, it writes a pointer to the first element of negativi.
The more serious problem is a buffer overflow in the loop
for (x = 0; x < 24; x++)
if (masivs[x] >= 0)
pozitivi[x] = masivs[x];
else
negativi[x] = masivs[x];
Here you use the same index x for both pozitivi, negativi and masivs. This index is only valid for masivs.
The loop as it works now with a single index x will not only put holes in the pozitivi and negativi arrays, but also go out of bounds of both.
The solution is to add another index, one each for the pozitivi and negativi arrays:
unsigned p = 0; // Index for positive number array
unsigned n = 0; // Index for negative number array
for (unsigned x = 0; x < 24; x++)
{
if (masivs[x] >= 0)
pozitivi[p++] = masivs[x];
else
negativi[n++] = masivs[x];
}
Afterwards you can use p and n as sizes for the corresponding array, to use when you write the result to the files.
And as mentioned in a comment to the question, the arrays aren't really needed which makes much of the code moot, and the whole program much simpler. And simplicity is better, as there's less chance of errors.
You can do a simple while(getline()) loop...
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <fstream>
int main()
{
int lineNumber, it = 0;
std::string line;
std::ifstream f("f.txt");
std::ofstream f1, f2;
f1.open("f1.txt");
f2.open("f2.txt");
while(std::getline(f, line)) //reads each line of f.txt ino a string
{
try
{
lineNumber = std::stoi(line);
}
catch(std::invalid_argument& e) //if value is not a number
{
std::cout << "VALUE IS NOT A NUMBER ON ITERATION " << it << '\n';
//std::abort();
continue;
}
catch(std::out_of_range& e) //if value is above +-2^32 +-1
{
std::cout << "VALUE OUT OF RANGE ON ITERATION " << it << '\n';
//std::abort();
continue;
}
if(lineNumber > 0)
{
f1 << lineNumber << '\n';
}
else
{
f2 << lineNumber << '\n';
}
it++;
}
f1.close();
f2.close();
}
This will get your desired output, file f1.txt containing all the positive numbers, and file f2.txt containing all the negative numbers.

Having trouble on this assignment where we need to use pointers and arrays to find the average, median, and mode of some numbers in a text file

I'm having some issues when trying to read in the values from a text file. The text file looks like this:
Murray Brandl 3
Christal Delamater 4
Zetta Kinlaw 7
Elia Roy 3
Delmer Bibb 4
Joannie Nevers 4
Roselle Gose 10
Jonathan Basnett 0
Marcel Earwood 12
Marina Newton 2
Magdalen Stephan 3
Deane Leach 5
Mariana Crosley 6
Darby Froman 5
Shonda Kyzer 4
Ilana Netto 4
Candida Magnani 1
Laurena Stiverson 2
Elouise Muir 4
Rene Holiday 2
We need to read these names and values into variables while using pointers and arrays. I am getting some errors such as this:
"Exception thrown: read access violation.
_Pnext was 0xFDFDFE01. occurred"
I don't know what this means or where to look to fix it. Below you can see my attempt so far, but I've only gotten to the averageMovie function because I am unable to read the text file in correctly. If you could help me out or point me in the right direction I would really appreciate it!
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include "Chapter 10 Movie Statistics.h"
using namespace std;
void averageMovie(int [], int);
int main()
{
ifstream infile;
infile.open("MovieStatistics.txt");
int numOfStudents = 0;
string first, last, line;
int movies;
int *numMovies;
string *names;
numMovies = new int[numOfStudents];
names = new string[numOfStudents];
if (!infile)
{
cout << "Error opening file";
}
else
{
while (getline(infile, line))
{
numOfStudents++;
istringstream ss(line);
ss >> first >> last >> movies;
}
for (int i = 0; i < numOfStudents; i++)
{
names[i] = first + last;
numMovies[i] = movies;
}
}
cout << "The number of students in the file is: " << numOfStudents << endl << endl;
averageMovie(numMovies, numOfStudents);
return 0;
}
void averageMovie(int array[], int size)
{
int total = 0,
average;
for (int i = 0; i < size; i++)
{
total += array[i];
}
average = total / size;
cout << "The average number of movies watched is: " << average;
}
int numOfStudents = 0;
// [snip]
int *numMovies;
string *names;
// [snip]
numMovies = new int[numOfStudents];
names = new string[numOfStudents];
Both of your arrays have zero elements; thus, every single access to them is broken. Increasing numOfStudents later makes no difference; it is too late.
What you're seeing is the technical result of utterly blasting your computer's memory.
Options:
Pick a number (e.g. 100) and use that; use up to 100 slots; stop the program before you go over that limit, though!
Precalculate how many you will actually need (one per line in the file, right?), then allocate the arrays
Use an array that expands on its own, i.e. a vector (though I'm betting your assignment does not permit this)

Store Matrix with integer from a text file into an array in c++

I have a file named matrices.txt that has two matrices that are 3 by 3.
They are:
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9
I'm trying the read from this file and store it into an array proto_matrix to later split that into two matrices.
The problem I'm having is that I can't store the numbers in the array.
My code is
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
int i = 0, j, k = 0, n, dimension;
cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
cin >> n;
dimension = n * n;
int proto_matrix[2 * dimension];
// make array of two matrices combined, this will be split into two matrices
ifstream matrix_file("matrices.txt");
while(matrix_file)
{
matrix_file >> proto_matrix[i];
}
matrix_file.close();
}
I tried debugging the code and it seems like the no integer is stored in the array, just random numbers.
This:
int proto_matrix[2 * dimension];
is a Variable Length Array (VLA), which is not Standard C++, but is supported by some compiler extensions. If compile with g++ -pedantic main.cpp, you will surely get an error.
That means that you need to dynamically allocate your memory, if you had to use an array.
You really don't though, C++ offers std::vector, which can achieve what you want relatively easily. I say relatively, because you have two matrices in one file, which makes parsing the file a bit tricky. Usually we put the one matrix in one file, and the other matrix to another file.
A 2D array can be represented as a 2D vector.
You want two matrices, thus two 2D vectors.
For that reason, I will use an array of size 2 (fixed size!), where every element is going to be a 2D vector.
Moreover, I will keep track of which matrix I am reading from the file right now (the first or the second), and how many rows I have read currently, in order to populate the correct cell of the matrix.
index is going to be equal to 0 or 1, to index the array.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
int i = 0, j, k = 0, n, dimension;
cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
cin >> n;
dimension = n * n;
vector< vector<int> > v[2];
v[0].resize(n);
v[1].resize(n);
// make array of two matrices combined, this will be split into two matrices
ifstream matrix_file("matrices.txt");
string line;
int rows_read = 0, cols_read = 0, index = 0;
while (std::getline(matrix_file, line))
{
std::istringstream iss(line);
int a, b, c;
if (!(iss >> a >> b >> c)) { break; } // error
// process tuple (a, b, c)
if(index == 0 && rows_read >= n)
{
rows_read = 0;
index = 1;
}
//cout<<"rows = " << rows_read << " " << index<<endl;
v[index][rows_read].push_back(a);
v[index][rows_read].push_back(b);
v[index][rows_read++].push_back(c);
}
matrix_file.close();
for(int i = 0; i < 2; ++i)
{
cout << "Printing matrix " << i << endl;
for(auto& matrix: v[i])
{
for(auto& number: matrix)
cout << number << " ";
cout << endl;
}
}
return 0;
}
Output:
Printing matrix 0
1 2 3
4 5 6
7 8 9
Printing matrix 1
1 2 3
4 5 6
7 8 9
PS: Unrelated to your problem, but What should main() return in C and C++? An int.
Based on my answer, I will post here a cleaner example, which achieves what your code tries to achieve: Read all the numbers in a 1D data structure (which will be split in two matrices somehow later).
So for that case, the code boils down to just this:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
int i = 0, j, k = 0, n, dimension;
cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
cin >> n;
dimension = n * n;
// make array of two matrices combined, this will be split into two matrices
vector<int> proto_matrix;
ifstream matrix_file("matrices.txt");
string line;
while (std::getline(matrix_file, line))
{
std::istringstream iss(line);
int a, b, c;
if (!(iss >> a >> b >> c)) { break; } // error
proto_matrix.push_back(a);
proto_matrix.push_back(b);
proto_matrix.push_back(c);
}
matrix_file.close();
for(auto& number: proto_matrix)
cout << number << "\n";
return 0;
}
You could just read all the values into a flat container (such as std::vector) and do the re-arrangement at a later point. The following code may give you an idea:
#include <vector>
#include <fstream>
#include <iostream>
int main() {
std::vector<int> values;
std::ifstream fp("matrices.txt");
for (int value; fp >> value; ) {
values.emplace_back(value);
}
std::cout << "I read " << values.size() << " values:\n";
for (auto && value : values) std::cout << value << " ";
std::cout << "\n";
}
Result:
$ clang++ matrixread.cpp -std=c++17
$ ./a.out
I read 18 values:
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
You don't increment i, thus always writing to the first element. It should be:
matrix_file >> proto_matrix[i++];

convert an array string to intger c++ (beginner)

I have a text file which that contains only numbers inside , and i have successfully pulled the numbers from the file and stored it inside an array:
my problem is that the array is "string" and i cant do mathematical operations on the array like Addition and Subtraction
I have tried to use atoi(array[i][j].c_str()) to convert it to intger
but it gives me only the first digit of a number!
my program looks like this for now , its a mess I know :(
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
ifstream iFile("input.txt");
string line;
string array[7][7];
for (int i=0;i<7;i++){
for (int j=0;j<6;j++){
getline(iFile,line);
if (!line.empty()){
array[i][j]=line;
}
else {
break;
}
}
}
cout<<"number of processes is: "<<array[0][0]<<endl;
cout<<"resource types: "<<array[1][0]<<endl<<endl;
cout<<"Allocation Matrix:"<<endl;
cout<<" A B C D"<<endl;
cout<<"0: "<<array[2][0]<<endl;
cout<<"1: "<<array[2][1]<<endl;
cout<<"2: "<<array[2][2]<<endl;
cout<<"3: "<<array[2][3]<<endl;
cout<<"4: "<<array[2][4]<<endl;
cout<<"Max Matrix:"<<endl;
cout<<" A B C D"<<endl;
cout<<"0: "<<array[3][0]<<endl;
cout<<"1: "<<array[3][1]<<endl;
cout<<"2: "<<array[3][2]<<endl;
cout<<"3: "<<array[3][3]<<endl;
cout<<"4: "<<array[3][4]<<endl;
cout<<"Need Matrix:"<<endl;
cout<<" A B C D"<<endl;
//cout<<"0: "<<array[3][1]+array[2][1]<<endl;
//int c= atoi(array[3][1].c_str());
//int c2= atoi(array[3][1].c_str());
//cout<<c+c2<<endl;
return 0;
}
my input.txt file looks like this:
5
4
0 0 1 2
1 0 0 0
1 3 5 4
0 6 3 2
0 0 1 4
0 0 1 2
1 7 5 0
2 3 5 6
0 6 5 2
0 6 5 6
1 5 2 0
1:0 4 2 0
edit:
note:if there is an empty line >> stop!
the program is based on banker algorithm which takes the first number from the input.txt as the numbers of of processes
then takes the second number as the numbers of of resource types
then takes the next numbers that there is no empty line between them as Allocation Matrix
then takes the next numbers that there is no empty line between them as max Matrix
and here is my problem when i want do Subtraction between Allocation Matrix and max Matrix because both are strings !
as for 1:0 4 2 0 it means do some operations with process number 1
You can use atoi but in c++ you have better options.
in c++ you can easily use stringstream to convert these types.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int convert_str_to_int(const string& str) {
int val;
stringstream ss;
ss << str;
ss >> val;
return val;
}
int main () {
string str = "1024";
int val = convert_str_to_int(str);
cout << "Val is: " << val << ", val/2 is " << val/2 << endl;
}

How to use string.substr() function?

I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
string a;
cin >> a;
string b;
int c;
for(int i=0;i<a.size()-1;++i)
{
b = a.substr(i,i+1);
c = atoi(b.c_str());
cout << c << " ";
}
cout << endl;
return 0;
}
If I am correct, the second parameter of substr() should be the length of the substring. How about
b = a.substr(i,2);
?
As shown here, the second argument to substr is the length, not the ending position:
string substr ( size_t pos = 0, size_t n = npos ) const;
Generate substring
Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position pos and has a length of n characters.
Your line b = a.substr(i,i+1); will generate, for values of i:
substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45 (since your string stops there).
What you need is b = a.substr(i,2);
You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45 due to the fact that you're using atoi() on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:
b = a.substr(i,2);
cout << b << " ";
In fact, the entire thing could be more simply written as:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cin >> a;
for (int i = 0; i < a.size() - 1; i++)
cout << a.substr(i,2) << " ";
cout << endl;
return 0;
}
Another interesting variant question can be:
How would you make "12345" as "12 23 34 45" without using another string?
Will following do?
for(int i=0; i < a.size()-1; ++i)
{
//b = a.substr(i, 2);
c = atoi((a.substr(i, 2)).c_str());
cout << c << " ";
}
substr(i,j) means that you start from the index i (assuming the first index to be 0) and take next j chars.
It does not mean going up to the index j.
You can get the above output using following code in c
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char *str;
clrscr();
printf("\n Enter the string");
gets(str);
for(int i=0;i<strlen(str)-1;i++)
{
for(int j=i;j<=i+1;j++)
printf("%c",str[j]);
printf("\t");
}
getch();
return 0;
}
Possible solution without using substr()
#include<iostream>
#include<string>
using namespace std;
int main() {
string c="12345";
int p=0;
for(int i=0;i<c.length();i++) {
cout<<c[i];
p++;
if (p % 2 == 0 && i != c.length()-1) {
cout<<" "<<c[i];
p++;
}
}
}
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
The string constructor can be used to get a copy of a substring.
string(const string& str, size_t pos, size_t n)
For example...
b = string(a, i, 2); // substring of a from position i, including 2 characters
This differs from substr in that the length n cannot be omitted. I offer this only as an alternative, not as an improvement.