How to properly read from a .csv? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am having memory trouble with my code, and figured out that my code was being read wrong. For example the last value is adding numbers, not sure why. Also the names aren't coming out right.
This is what the output is looking like:
4101,BRAEBURN02.07682e-3172.07691e-317
4021,DELICIOUS02.07682e-3172.07691e-317
4020,DELICIOUS02.07682e-3172.07691e-317
4015,DELICIOUS02.07682e-3172.07691e-317
4016,DELICIOUS02.07682e-3172.07691e-317
4167,DELICIOUS02.07682e-3172.07691e-317
4124,EMPIRE,1,1.14,145.202.07682e-3172.07691e-317
4129,FUJI02.07682e-3172.07691e-317
4131,FUJI02.07682e-3172.07691e-317
As you can see the Empire was separated properly with the exception of the the last value.
Here's my code: the cout part was just for my personal use to see if the values were being inputted properly.
int main()
{
string name;
double price;
int by_weight;
double inventory;
int plu_code;
ifstream infile;
infile.open("inventory.csv");
while(!infile.eof())
{
stringstream ss;
string line = "";
getline(infile,line);
Tokenizer tok(line, ",");
ss << line;
ss >> plu_code >> name >> by_weight >> price >>inventory;
cout << plu_code<<"" <<name<<"" << by_weight<<"" << price <<""<<inventory<<"\n";
table[plu_code] = new Product(plu_code, name,by_weight, price,inventory);
numProducts++;
}
return 0;
}

The Empire line works because it's the only one whose name contains no whitespace. When you read strings from a stream, they are delimited by whitespace, so you only get the first word. If there are more words after that, then reading a double or other numeric type will fail because the stream is still pointing at non-numeric characters. You are not testing that your input operations succeeded, but it should have been obvious from your output.
I'm not sure what effect your Tokeniser class is supposed to have here. But perhaps have a look at this SO question for tokenising commas out of the stream. You can use a single getline call with a comma delimiter to read the name, and then normal << operator for the others.
[Edit] In fact, after cleaning up your question layout I notice that the Empire line doesn't work. It's reading the rest of the line as the name, and then still outputting uninitialised values. Which suggests to me your Tokeniser doesn't do anything at all.

Related

how to parse line into number and string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 11 months ago.
Improve this question
I would like to parse a sentence beginning with a number:
2 random sentece.
5 another one.
8 this is really long sentence.
Into int number holding the beginning number and the rest in std::string sentence. So in the first line, the parsing output will be number == 2 and sentence == "random sentence". The input is read from stdin, but the classical std::cin >> number >> sentence does'n work, since the parsing of string would end once it reaches a space. But I want to make the string beginning after the initial number to the end of line \n. So, how to do it in C++?
You can make use of std::getline and std::istringstream as shown below. In particular in the given program, std::getline is used to read line by line and std::istringstream is used to read first the integer and then the remaining sentence.
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string sentence;
int inputInt = 0;
//read line by line
while(std::cin >> inputInt && std::getline(std::cin, sentence))
{
std::cout<< inputInt <<"-----"<<sentence<<std::endl;
//do the check here
}
}
Demo

Remove whitespace in C++ string doesn't work [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have read these two questions already:
Remove spaces from std::string in C++
remove whitespace in std::string
For some reason, I can never get the solutions to work correctly. In my program, I collect input from the user and pass it to an std::string. From there, I want to remove all of the spaces in it. For example, if the user inputs "3 + 2", I would like it to change to "3+2".
What happens is, whatever is before the first string is kept. Here is my program:
#include <iostream>
std::string GetUserInput() {
std::cout << "Please enter what you would like to calculate: ";
std::string UserInput;
std::cin >> UserInput;
return UserInput;
}
int PerformCalculation(std::string Input) {
Input.erase(std::remove_if(Input.begin(), Input.end(), ::isspace), Input.end());
std::cout << Input;
return 0;
}
int main() {
std::string CalculationToBePerformed = GetUserInput();
int Solution = PerformCalculation(CalculationToBePerformed);
return 0;
}
So when I run this program and type in "3 + 2", the output is "3".
Here is my console:
Please enter what you would like to calculate: 3 + 2
3
Process finished with exit code 0
I cannot figure out how to resolve this. I even tried using a solution that involved using a regex to remove all the \s characters, and that gave me the same issue.
To read the complete line (up to terminating \n), you need to use e.g. std::getline(std::cin, UserInput);. Otherwise, you're currently reading text up to first whitespace character.

Extracting integers from a ID string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to get the number 001 from the string UID001 (The user will always enter "UIDnnn"). I tried using cin.get and cin.ignore with delimiters but with no results. What is the most effective way to extract the integers from a string?
Well, the simplest c++ standard compliant solution seems to be as mentioned in my comment.
Read the ID value as a std:string:
std::string ID;
std::cin >> ID;
Get the substring with the number part:
std::string numpart = ID.substr(3);
Convert it to a numerical value:
int idnum = std::stoi(numpart);
This is one of those places that scanf and company really work well:
scanf("UID%d", &number);
With iostreams it's a bit uglier, but I'd consider something like:
for (int i=0; i<3; i++) {
char ch;
cin.get(ch);
}
cin >> number;

user enters String instead of Int [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
We have tried to search this problem but we haven't found any answers. If The user inputs a string variable when the system requires a integer how do you evade the problem with out using a while loop?
{
int grade_var=0,grade_1=0,sum=0;
cout<<"Enter the number of grades you have:\t";
cin>>grade_var;
for(int i=1;i<=grade_var;i++)
I don't wish to do a while loop for my program has a lot of integer insertions and want to know an easier way to correct rather than while loops?
While loops are generally the way to go.
However, to keep the code clean, you may want to consider putting said while loop into a helper function, so you can just call PollForIntegerInput(string prompt) from anywhere in your code, and then handle that input in one place. There is almost never a reason you should be duplicating an input loop like that.
As for a truly nonlooping answer, I have none.
Calling operator>> on a stream returns the stream itself, which can be converted to bool to check if the stream is in a good state. If a bad extraction happens, the stream is not in a good state. So you can do something like this:
if (cin >> grade_var)
This will check that it was successful. You can just negate the condition to find it if it wasn't successful. How you handle this condition is up to. Maybe you'll return early on failure. If you want to reprompt the user for correct input, however, you'll need a loop.
It's not too clear what your problem is, but...
It's almost always poor design to input the number of data
points which will follow. If you expect a series of int, for
example:
std::vector<int> grades;
int grade;
while ( std::cin >> grade ) {
grades.push_back( grade );
}
It doesn't get much simpler.
If you do want to insist on an exact number of input, outputting
an error when the user inputs something incorrect, the usual
pattern would be:
std::vector<int> grades;
while ( grades.size() != targetNumber ) {
int grade;
while ( !(std::cin >> grade) ) {
std::cout << "Integer wanted" << std::endl;
std::cin.clear();
std::cin.ignore( INT_MAX, '\n' );
}
grades.push_back( grade );
}
Still no for. (In fact, for loops with input are very, very
rare.)

c++ Parsing prices of a text file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to parse the following file so it takes the item as a string then skip the # sign and then take the price as a float.
text file:
hammer#9.95
saw#20.15
shovel#35.40
how would I go about doing this?
In case when you have std::string in presented format you could use something like this:
std::string test {"test#5.23"};
std::cout << std::stof(std::string{test.begin() + test.rfind('#') + 1, test.end()});
Note that std::stof is C++11 function
Read the file line by line into a string. Find # and parse second part as float.
std::ifstream file("input.txt");
for (std::string line; std::getline(file, line); )
{
auto sharp = line.find('#'); // std::size_t sharp = ...
if (sharp != std::string::npos)
{
std::string name(line, 0, sharp);
line.erase(0, sharp+1);
float price = std::stof(line);
std::cout << name << " " << price << "\n";
}
}
Note: I didn't some error checking, do them yourself as an exercise. and also you should know about std::string, std::ifstream, std::getline and std::stof.