- #1
elmessican
- 6
- 0
What can I use to replace stoi since the homework program won't accept it? I'm trying to read a string and display it as an integer. I know I have to use stringstream but have no idea how.
Code:
//ReadData.cpp
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
int main() {
//Define the required variables
string title, head1, head2, s;
vector<string> data;
vector<int> point;
//Prompt and read the title of the data
cout << "Enter a title for the data: " << endl;
getline(cin, title);
cout << "You entered: " << title << endl;
cout << endl;
//Prompt and read the headers of two columns
cout << "Enter the column 1 header: " << endl;
getline(cin, head1);
cout << "You entered: " << head1 << endl;
cout << endl; cout << "Enter the column 2 header: " << endl;
getline(cin, head2);
cout << "You entered: " << head2 << endl;
cout << endl; //Use while loop to read the data points until user enters -1
while (1) {
cout << "Enter a data point (-1 to stop input): " << endl;
getline(cin, s);
if (s == "-1") {
break;
}
if (s.find(',') == -1) {
cout << "Error: No comma in string." << endl;
cout << endl;
}
else {
int count = 0;
for (int i = 0; i<s.length(); i++) {
if (s.at(i) == ',') {
count++;
if (count > 1) {
break;
}
}
}
//If the input have single ',', then display the data string and data integer
if (count == 1) {
data.push_back(s.substr(0, s.find(',')));
point.push_back(stoi(s.substr(s.find(',') + 1, s.length() - 1)));
cout << "Data string: " << s.substr(0, s.find(',')) << endl;
cout << "Data integer: 6" << stoi.s.substr(s.find(',') + 1, s.length() - 1) << endl;
cout << endl;
}
else {
//Display the appropriate error message
cout << "Error: Too many commas in input." << endl;
cout << endl;
}
}
}
//Display the data in the required format
cout << "\t" << title << "\t" << endl;
cout << head1 << "\t|\t" << head2 << endl;
for (int i = 0; i<data.size(); i++) {
cout << data[i] << "\t|\t" << point[i] << endl;
}
for (int i = 0; i<data.size(); i++) {
cout << data[i] << " ";
for (int j = 0; j<point[i]; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}