c++ Parsing prices of a text file [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 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.

Related

How to fix this code to read this file in C++? [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 1 year ago.
Improve this question
Here's my code, which should be able to read the file, but it gives me this:
Error: Invalid format in file
What's wrong in this code?
int main()
{
std::map<std::string, std::vector<std::string>> routes;
print_rasse();
std::string inp;
std::cout << "Give a name for input file: ";
std::getline(std::cin, inp);
std::ifstream file(inp);
std::string row;
if ( not file ) {
std::cout << "Error: File could not be read." << std::endl;
return EXIT_FAILURE;
}
while(getline(file, row)){
if (count(row.begin(), row.end(),';'+!1)){
std::cout << "Error: Invalid format in file." << std::endl;
return EXIT_FAILURE;
}
}
}
The .txt file which I'm trying to read contains this:
West;Pyynikintori;0
West;Tuulensuu;0.5
West;Keskustori;1.5
West;Koskipuisto;1.8
West;Rautatieasema;2.2
West;Tulli;2.5
West;Sammonaukio;2.8
East;Sammonaukio;
East;Kaleva;0.2
East;Uintikeskus;0.3
East;Kalevanrinne;0.6
East;Hakametsa;1
East;Turtola;3
East;Hallila;5
East;Hervanta;7
East;Hervannan kampus;7.1
South;Hervannan kampus
South;Etela-Hervanta;0.4
South;Hervantajarvi;0.7
Hospital;Sammonaukio
Hospital;Kalevan kirkko;0.1
Hospital;Hippos;0.4
Hospital;TAYS;0.6
Hospital;Kaupin kampus;0.7
In this statement:
if (count(row.begin(), row.end(),';'+!1))
!1 is effectively the same as 0, so ';'+0 is just ';'. The statement is effectively this:
if (count(row.begin(), row.end(), ';'))
It is counting the number of ; characters in the row. An integer implicitly converts to a bool, where 0 is false and non-0 is true. So, if there are any matching characters in the row, the if will evaluate as true, otherwise as false.
Since each line in the .txt file shown has 2 ; characters in it, count() will return 2, thus the if will be true, and so the code will display the error message.
You probably meant to do this instead:
if (count(row.begin(), row.end(), ';') != 2)

Matching lines in a text-file with a starting identifer [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 5 years ago.
Improve this question
So I'm a bit stumped on this, I'm reading a file with two types of lines that contain data, and they are started by a number followed by a comma. I need a way in order to match the lines with the same starting digit into a single line and output that. How would I even get started?
I'd do this by reading each line in two parts: the stuff before the comma, and the stuff after it.
Then I'd have a map (or unordered_map) with the value before the comma as the key, and the rest as the value associated with it.
std::map<std::string, std::string> data;
std::string key, value;
while (std::getline(infile, key, ',')) {
std::getline(infile, value);
data[key] += value;
}
Then (presumably) you'd want to write out the values:
for (auto const &v : data)
std::cout << v.first << ":" << v.second << "\n";

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.

Parsing strings in variable and store them to a new variable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I need to parse the following, which is stored in a variable, and extract only Names. These names should be placed in a new variable (all together separated by dot (.)). Any ideas?
Name : Mike Anderson\n
Age : 43\n
Name : Andie Jameson\n
Age : 35\n
The expected output should be a variable with content: Mike Anderson.Andie Jameson
Thank you.
There will be many useful methods for your situation.
This code is just one of them. I used std::istringstream, string::find().
int main()
{
//Originally, each data is from your source.
//but, this is just sample.
std::istringstream input;
input.str("Name : Mike Anderson\nAge : 43\nName : Andie Jameson\nAge : 35\n");
//to find pattern
std::string name_pattern = "Name : ";
std::size_t found = std::string::npos;
for (std::string line; std::getline(input, line); ) {
found = line.find(name_pattern);
if (found!=std::string::npos)
{
//write on file for 'directory'
std::string only_name(line, found + name_pattern.length() );
std::cout << "\nName : " << only_name;
continue;
}
}
getchar();
}
This code will print below like,

How to properly read from a .csv? [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 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.