I have a string of different integers separated by a comma. For example "45,67,2,3,8,9,123,5,6,3,9,4,7,2,4,4,5,69,9,99". I want to read this line as a stringstream and put integers to the vector of integers. On the console, it displays "no response on stdout".
The code looks as follows:
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
stringstream myString;
vector<int> of_integers;
char ch;
int a;
for(int k = 0; k<str.size(); k++)
{
myString >> a >> ch;
of_integers[k] = a;
}
return of_integers;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str); //function parseInts
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
The working code:
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
stringstream myString(str);
int size = str.size();
vector<int> of_integers;
char ch = ',';
int a=0;
while(myString.eof()!=1)
{
myString >> a >> ch;
of_integers.push_back(a);
}
return of_integers;
}
int main() {
string str;
cin >> str;
vector<int> integers;
integers = parseInts(str);
for (int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
Thanks for #jpmarinier, for referencing an useful stringstream function .eof() that detects when the stringstream ended.
The code worked well.
Input:
45,67,2,3,8,9,123,5,6,3,9,4,7,2,4,4,5,69,9,99
Output:
45
67
2
3
8
9
123
5
6
3
9
4
7
2
4
4
5
69
9
99
Related
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
cin.ignore();
while(t--){
string s;
getline(cin,s);
int i =0;
int count =0;
while(i<s.size()){
if(s[i]!=' '){
//cout<<count<<":";
s[count++]=s[i];
}
i++;
}
s[count]='\0';
cout<<s<<endl;
}
return 0;
}
Why in the end String is not terminating with '\0'?
For Input:
2
geeks for geeks
g f g
your output is:
geeksforgeeksks
gfgg f g
To remove a character from a string, you should use erase.
See the remove-erase idiom.
std::string is not a C-style null terminated string (but you can obtain one from it). As such, inserting a null character will not terminate it. If you want to truncate a string from the end, you can simply resize() it. Otherwise, if you want to remove characters, you can erase() them.
You say you want to remove spaces. To do that with your existing code, simply replace s[count]='\0'; with s.resize(count);, eg:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
cin.ignore();
while (t--){
string s;
getline(cin, s);
int i = 0;
int count = 0;
while (i < s.size()){
if (s[i] != ' '){
//cout<<count<<":";
s[count++] = s[i];
}
i++;
}
s.resize(count);
cout << s << endl;
}
return 0;
}
However, a better way to handle this would look more like this:
#include <iostream>
#include <string>
int main()
{
int t;
std::cin >> t;
std::cin.ignore();
while (t--){
std::string s;
std::getline(cin, s);
std::string::size_type idx = 0;
while ((idx = s.find(‘ ‘, idx)) != std::string::npos){
s.erase(idx, 1);
}
std::cout << s << std::endl;
}
return 0;
}
Alternatively:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
int t;
std::cin >> t;
std::cin.ignore();
while (t--){
std::string s;
std::getline(cin, s);
std::string::iterator iter = std::remove(s.begin(), s.end(), ‘ ‘);
s.erase(iter, s.end());
std::cout << s << std::endl;
}
return 0;
}
I'm not getting any errors, just an infinite loop! Here's my code:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<fstream>
#include<assert.h>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
int sum{ 0 }, number;
vector<int> numbers;
string word;
fstream file;
file.open("file1.txt", fstream::in);
while (true) {
file >> number;
if (file.eof()) {
numbers.push_back(number);
break;
}
else if (file.fail()) { file >> word; }
else if (file.bad()) exit(1);
else numbers.push_back(number);
}
for (int x : numbers) sum += x;
cout << sum << "\n";
}
The file I am reading from:
words 32 jd: 5 alkj 3 12 fjkl
23 / 32
hey 332 2 jk 23 k 23 ksdl 3
32 kjd 3 klj 332 c 32
You are not reading the integers properly, or correctly checking if operator>> is successful before using number. And more importantly, you are not clearing the stream's error state when non-integer input is encountered by operator>>.
Try something more like this instead:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <stdexcept>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
int sum = 0, number;
vector<int> numbers;
string word;
ifstream file("file1.txt");
while (file >> word) {
try {
number = stoi(word);
}
catch (const std::exception &) {
continue;
}
numbers.push_back(number);
}
if (file.fail() && !file.eof())
exit(1);
for (int x : numbers)
sum += x;
cout << sum << "\n";
keep_window_open();
return 0;
}
Live Demo
See if this works:
#include<iostream>
#include<fstream>
#include <cctype> // isdigit
#include<string>
#include<vector>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
int sum{ 0 };
string number; // new
vector<int> numbers;
fstream file;
file.open("file1.txt", fstream::in);
while (true) {
file >> number;
if (file.eof())
break;
if (isdigit(number[0])) // new
numbers.push_back(stoi(number));
}
file.close();
for (int x : numbers) sum += x;
cout << sum << "\n";
return 0;
}
I want to input
1 2
3 4 5
a: 1 2
b: 3 4 5
If I use this way, I will get b is also 1 2, I tried cin.ignore(), it doesn't work.
Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main(){
char a[3];
char b[5];
cin>>a;
cin>>b;
cout<<b[0]<<endl;
return 0;
}
You can use a loop to read an array of characteres and to stop that loop, choose some character as a mark (but you will have to use Enter after it) or use EOF which can be occur by ctrl+d on linux or ctrl+z on windows, as follows
#include <iostream>
int main(){
char a[50];//to hold an array of 49 chars
int i{};
char end {'a'};//non space char
while( std::cin >> a[i] && a[i] != end)
i++;
a[i] = '\0';
std::cout << a << std::endl;
return 0;
}
Or use std::getline(). It's better. You won't need a thing but an Enter
#include <iostream>
#include <string>
int main(){
char a[50];
std::string temp{};
std::getline(std::cin, temp);
int i{ -1 };
while( ++i < temp.size()) a[i] = temp[i];
a[i] = '\0';
std::cout << a << std::endl;
return 0;
}
I have written this program in C++ that reads an input.txt file containing these numbers
7
18
5
15
131
11
13
287
The program adds to the array the first value 7, then in the next seven numbers there's random values (such as 0, 4659174, 0, 4778144 etc) and then it prints 7 and 18 and then eight more random numbers and then you can see printed 7, 18, 5 and so on until the last eight numbers are what is actually in the input.txt file.
How can I get it to show only the numbers that are present in the input.txt file instead of all of these random values? Here's my code so far:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <stdlib.h>
using namespace std;
int main(){
int myArray[10];
int i = 0;
ifstream input("input.txt");
string number = "";
char next_letter = '\0';
while (input.get(next_letter)){
while (isdigit(next_letter) && !input.eof()){
number += next_letter;
input.get(next_letter);
}
int val = 0;
val = atoi(number.c_str());
myArray[i++] = val;
for(int i = 0; i < 8; i++)
{
cout << "array contents are: " << myArray[i] << endl;
}
number = "";
}
return 0;
}
Please consider the following code:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
int main(){
long myArray[10];
int i = 0;
ifstream input("input.txt");
string number = "";
const int MAX_LEN = 100;
char number_str[MAX_LEN];
while(input.getline(number_str, MAX_LEN - 1, ' ')){
char* end;
myArray[i++] = std::strtol(number_str, &end, 10);
}
cout << "array contents is: ";
for(int k = 0; k < i; k++)
{
cout << myArray[k] << " ";
}
cout << endl;
return 0;
}
The getline does the reading until the ' ' and conversion is done by strtol. Please note that it input numbers are long int by default.
I'm trying to split this a string with a comma as a delimeter. I put a string "Smith,Erdos,William" and it just outputs "William" but not Smith and Erdos. There must be something wrong here that I just can't see, can anyone help?
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main() {
int numScenarios(0);
int numPapers(0);
int numWriters(0);
std::vector<std::string> paperTitles (1);
std::vector<std::string> paperAuthors (1);
std::vector<std::string> splitAuthors (1);
std::string token;
std::string input;
std::cin >> numScenarios;
std::cin >> numPapers >> numWriters;
for (int i(0); i < numPapers; ++i) {
std::getline(std::cin,input);
std::istringstream iss(input);
while(getline(iss,token,','));
{
std::cout << token << std::endl;
}
//paperTitles.push_back(input);
//input = '\0';
}
for (int i(0); i < numWriters; ++i) {
getline(std::cin,input);
paperAuthors.push_back(input);
input = '\0';
}
return 0;
}
while(getline(iss,token,',')); // <== look closely