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 using the following code to save the array data into file
ofstream out;
out.open("Database.txt", ios::trunc);
for(int t=0; t<Data_Counter; t++)
{
out << t <<endl;
out << Data[t].getName() << endl;
out << Data[t].getID() << endl;
}
out.close();
now I want to retrieve the data back in the same array positions. What do I need to add in the following code to make it work:
ifstream in;
in.open("\Database.txt", ios::in);
// what logic to use
in.close();
To read to the end of your file use some code like this
int index;
string name, id;
while (in >> index >> name >> id)
{
// do something with index, name and id
}
This works because in >> ... is only true when the read was successful. So when you get to the end of the file in >> ... will be false and the while loop will terminate.
I am assuming that there's no whitespace in your names and ids. If that's not the case then you have a slightly more difficult problem.
Another way is to take advantage of the fact that your input is separated by newlines and do this
string index, name, id;
while (getline(in, index) && getline(in, name) && getline(in, id))
{
// do something with index, name and id
}
The advantage of this version is that it will work if you have spaces in your name. The disadvantage is that getline only works with strings. So you have to convert index from a string to an integer.
Just to get you on track,
int xyz;
in>>xyz;
This will read the integer at your first line, which you stored as "t". Now try to loop and read strings, line by line, and store them. Good luck.
Related
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 5 months ago.
Improve this question
I'm trying to solve this question below:
Write code to read a list of song durations and song names from input. For each line of input, set the duration and name of newSong. Then add newSong to playlist. Input first receives a song duration, then the name of that song (which you can assume is only one word long).
Input example:
424 Time
383 Money
-1
This is the code that I used:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Song {
public:
void SetDurationAndName(int songDuration, string songName) {
duration = songDuration;
name = songName;
}
void PrintSong() const {
cout << duration << " - " << name << endl;
}
int GetDuration() const { return duration; }
string GetName() const { return name; }
private:
int duration;
string name;
};
int main() {
vector<Song> playlist;
Song newSong;
int songDuration;
string songName;
unsigned int i;
cin >> songDuration;
while (songDuration >= 0) {
/* Solution is below */
getline(cin, songName);
newSong.SetDurationAndName(songDuration, songName);
playlist.push_back(newSong);
/* Solution is above */
cin >> songDuration;
}
for (i = 0; i < playlist.size(); ++i) {
newSong = playlist.at(i);
newSong.PrintSong();
}
return 0;
}
This is the message I get when I try to run my code:
Can someone please help me remove the extra space from the method? I don't know how to remove this space, I tried everything I know.
On this statement:
cin >> songDuration;
Reading stops when a non-digit character is encountered, such as the whitespace following the number. The whitespace is left in the input buffer for subsequent reading.
Then this statement:
getline(cin, songName);
Reads from the input buffer until a line break is encountered. As such, the whitespace that is present between the number and the name ends up in the front of the songName variable. That is the whitespace you are seeing in your output.
The solution is to ignore the whitespace before reading the songName.
You can use the std::ws I/O manipulator for that purpose, eg:
#include <iomanip>
...
getline(cin >> ws, songName);
However, the instructions clearly state the following about the song name:
the name of that song (which you can assume is only one word long)
So, you can alternatively use operator>> to read in the songName. It will ignore the leading whitespace for you:
cin >> songName;
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 2 years ago.
Improve this question
I am trying to stop the loop when user gives a blank line, otherwise push name and score to a vector pair. But this code is not working.
Input format:
<name><score>
e.g.:
Akash 45
My code is below:
int m;
cin>>m;
vector<pair<string,int>>player;
string name;
int score;
while(1)
{
cin>>name;
if(name.empty())
break;
cin>>score;
player.push_back(make_pair(name,score));
}
Also , I have tried the following:
if(name.length()==0)
while(getline(cin,name))
if (name=="")
None of them worked.
Can anyone help me?
`std::cin >>`
does not return with empty input. When the user wrote just the "Enter" key, the std::cin still wait.
I made the test, this is working :
std::getline(std::cin, name);
if(name.empty())
break;
Edit :
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::pair<std::string, int>>player;
std::string name;
int score;
while (1)
{
std::getline(std::cin, name);
if (name.empty())
break;
std::cin >> score;
player.push_back(make_pair(name, score));
// clear the std::cin buffer else the next std::getline won't wait next input
std::cin.seekg(0, std::ios::end);
std::cin.clear();
}
return 0;
}
the
std::cin.seekg(0, std::ios::end);
std::cin.clear();
fix the problem of the second std:getLine
operator>> ignores whitespace, and line breaks are treated as whitespace, so cin>>name will never return a blank string (baring an input failure).
To accomplish what you are attempting, you need to use get::getline() instead to read an entire line at a time. You can then test for blank lines, and can use std::istringstream to parse values from each non-blank line, eg:
vector<pair<string,int>> player;
string line, name;
int score;
while (getline(cin, line) && !line.empty())
{
istringstream iss(line);
if (iss >> name >> score)
player.push_back(make_pair(name, score));
}
There's a small program to demonstrate you how to achieve so:
#include <iostream>
#include <vector>
int main(void) {
std::string name;
std::vector<std::string> nameList;
std::getline(std::cin, name); // statement X
nameList.push_back(name);
for (; ;)
if (name.empty())
break;
else {
std::getline(std::cin, name); // recalling statement X again
nameList.push_back(name);
}
for (int i = 0; i < nameList.size(); i++)
std::cout << nameList[i] << std::endl;
return 0;
}
First of all, let the user input something before going inside the loop directly. As soon as the user hits Enter, the loop will be broken when name.empty() conditions becomes true and returns true and break statement is executed.
In the other hand, as long as the user will hit the Enter key and keep writing something line-by-line, the loop will be executed.
Notice that I've used a For loop in this case, you could do the same trick with a While loop as shown:
while (true)
if (name.empty())
break;
else {
std::getline(std::cin, name); // recalling statement X again
nameList.push_back(name);
}
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 4 years ago.
Improve this question
I have been asked to develop program to count no. of lines and words in the file, this is my trial, my teacher said that I cant use >> operator for counting words and comparing but I could not handle it.
#include <iostream>
#include <fstream>
using namespace std;
int numberLines = 0;
int numberWords = 0;
void numberOfLines(){
cout<<"number of lines is " << numberLines << endl;
}
void numberWords(){
cout << "number of words is " << numberWords <<endl;
}
int main(){
string line;
char a = '';
ifstream myfile("files.txt");
if(myfile.is_open()){
while(!myfile.eof()){
getline(myfile,line);
cout<< line << endl;
numberLines++;
}
if ( a == ' '){
NumberWords++;
}
}
myfile.close();
}
numberOfLines();
numberOfWords ();
}
What you can do is add a 3rd argument to getline(). This lets it pull data from the stream until it hits a character. Doing getline(cin, line, ' ')takes all the data until the next and puts it into line. Your code might look like:
while(getline(inFile, line))
{
++numlines;
stringstream lineStream(line);
while(getline(lineStream, line, ' '))
{
++numWords;
}
}
The outer loop goes through the file and stores each line into line, then the inner goes through that line and counts each space. which correlates to a word.
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
How to repeat std::getline() as user number input like this method:
std::string num;
std::cout << "How many subjects you want to sum: ";
std::getline (std::cin,num);
Then take user number input and repeat std::getline() many times as input to sum all the subjects marks user will input them after the first questions.
Prefer not to use std::getline for inputting numbers.
You need a standard pattern:
int quantity = 0;
std::cout << "Enter quantity of subjects to sum: ";
std::cin >> quantity;
int sum = 0;
for (int i = 0; i < quantity; ++i)
{
int value;
std::cin >> value;
sum += value;
}
A common data input format is to specify the quantity as the first number on a single line.
The data will follow on subsequent lines, usually one number per line.
The operator>> will skip whitespace (including newlines).
Edit 1: Using getline
If you must use getline, remember that it only reads in strings (characters). If you want to numbers, you will have to convert from text representation to internal representation.
int quantity;
std::string text_line;
std::cout << "Enter quantity to sum: ";
std::getline(std::cin, text_line);
int sum = 0;
// Extract number from the text
{
std::istringstream text_stream(text_line);
text_stream >> quantity;
}
for (int i = 0; i < quantity; ++quantity)
{
std::getline(std::cin, text_line);
std::istringstream text_stream(text_line);
int value = 0;
text_stream >> value;
sum += value;
}
Notice the difference in the number of lines.
Also, notice the usage of std::istringstream. It looks like using std::cin in the first example.
There are other techniques to convert text representation of numbers to internal representation. These are left to the reader to research.
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 6 years ago.
Improve this question
Non-working code:
#include<iostream>
#include<fstream>
#include<string>
int main(){
int id; string name;char comma ; double money;
ifstream read("testfile.csv");
while (read >> id >> comma>> name >> comma >> money)
{cout << id <<comma<<name<<comma<<money<< endl ;}
read.close();
_getch();
return 0;}
The csv file data & structure:
1,user1,999
2,user2,33
3,user3,337
But, the following works fine. Why so?
while (read >> id >>comma>>name)
{cout << id<<comma<<name <<endl ;}
When you read a string using >>, it reads a space delimited string. If there is no space in the text you read, it will read until the end of the line (as newline is a space).
Because of this the "parsing" of the input will after a little while be out of sync with the contents from the file, and will lead to an error when attempting to read one of the numbers.