C++ - Repeat std::getline() as user integer input? [closed] - c++

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.

Related

How do I remove the extra space on the output from this method [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 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;

How to read space separated input in C++ When we don't know the Number of input

I have read the data like the following
7
1 Jesse 20
1 Jess 12
1 Jess 18
3 Jess
3 Jesse
2 Jess
3 Jess
Here the 7 is the number of input lines and i have to read the space separated input in c++, How can i read those input where we don't know how to separate them. this line contains string and integers.
Here is one example, that uses operator>> and std::string:
int x;
std::string name;
int y;
int quantity;
std::cin >> quantity;
for (int i = 0; i < quantity; ++i)
{
std::cin >> x;
std::cin >> name;
std::cin >> y;
}
The above will work for all lines that have 3 fields, but not with the lines without the last field. So, we'll need to augment the algorithm:
std::string text_line;
for (i = 0; i < quantity; ++i)
{
std::getline(std::cin, text_line); // Read in the line of text
std::istringstream text_stream(text_line);
text_line >> x;
text_line >> name;
// The following statement will place the text_stream into an error state if
// there is no 3rd field, but the text_stream is not used anymore.
text_line >> y;
}
The root cause is that the missing 3rd field elements will cause the first example to be out of sync because it will read the 1st column of the next line for the 3rd field.
The second sample of code makes the correction by reading a line at a time. The input operations are restricted to the text line and will not go past the text line.

Why is my program getting a runtime error when I execute my code? [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 8 years ago.
Improve this question
This program is working without the loop, however when I implement the loop, I get a runtime error. I think it might have something to do with my cin.getline but I really have no idea :/ any help would be great thank you!
#include <iostream>
using namespace std;
#include <string>
#include <iomanip>
int main ()
{int ans, z;
z=1;
cout << "How many times would you like to execute this string program? " << endl;
cin >> ans;
while (z <= ans)
{
int x, i, y, v;
string answer1, str3;
string mystring, fname, lname;
i=0;
y=0;
cout << "Please enter your first and last name: ";
getline(cin, answer1);
cout << endl;
x=answer1.length();
for (int i = 0; i < x; i++)
{
cout << answer1[i] << endl;
if (isspace(answer1[i]))
{
y=i;
}
}
cout << endl << endl;
cout << setw(80) << answer1;
mystring = answer1;
v=answer1.find(" ", 0);
fname=mystring.substr(0, y);
lname=mystring.substr(v, x);
cout << "First name: " << fname << endl;
cout << "Last name: " << lname << endl;
mystring=lname+','+fname;
cout << setw(80) << mystring;
z++;
}
return 0;
}
The error happens in this line:
lname=mystring.substr(v, x);
where v happens to have a very large value. So how does your program get there, and how does v get this value? v has value std::string::npos, which is an error code meaning, in this case, that the space you were looking for wasn't there. That this is the case has to do with the difference between formatted and unformatted input and the fact that you're mixing them.
Formatted input means treating an input stream as a stream of tokens. Leading whitespace -- all whitespace, whether space, tab, or newline -- is skipped, and where the token ends, there does the input. One example of formatted input is
cin >> ans;
For formatted input, everything that doesn't fit its pattern looks the same. Whether std::istream::operator>>(int) encounters a space, a tab, a newline, an 'a' or a 'z', that's just the end of the token, and there it stops reading. For example, if you have
int x;
std::string s;
std::cin >> x >> s;
and feed it the input 123abc, then x will have the value 123, and s will be "abc". Crucially, this means that if the user answers
cin >> ans;
with a number and newline, the encountered character after the number -- a newline -- remains in the stream.
Unformatted input, by contrast, means treating an input stream as a stream of characters. For unformatted input functions, whitespaces are just another character, and unless the unformatted input function defines a special meaning for them, it will treat them the same as any other character. An example of unformatted input is
getline(cin, answer1);
which is shorthand for
getline(cin, answer1, '\n'); // that is to say, the delimiter
// has a default value of '\n'
(just to make it clear that the newline character '\n' has a special meaning in this case). getline, used this way, will read from the stream until it encounters a newline.
And therein lies your problem. After the previous, formatted input function, there is stuff left in the stream that you don't care about. It is probably just a newline (although if the user provided 123abc, it will be abc\n), in which case getline will give you an empty string -- there's an empty line in the stream, so what else can it do?
There are several ways to deal with this condition. One is to say
#include <iostream>
#include <limits>
cin.ignore(numeric_limits<streamsize>::max(), '\n');
This is essentially saying: ignore everything up to the next newline (the numeric_limits<streamsize>::max() is a very large number that cin.ignore treats as infinity). Another is
cin >> ws;
which says: "ignore everything up to the next non-whitespace character", although this will ignore leading spaces in the next line, and it will not ignore abc if the user provided 123abc. In your case, I believe there is no reason to change gears from formatted input -- you don't want a line but first and last names. I suggest using
string fname, lname;
cin >> fname >> lname;
This will also eliminate the other error (that you're using an error code as string index), because you won't have to search for a space in the string that may not be there.
Do
cin >> ans;
cin >> std::ws;
before the while loop. Also, check
v=answer1.find(" ", 0);
for
std::npos
which is the value returned if find was unsuccessful.

How to get a certain element from an input (C++)

I am new to programming in C++.
I am trying to ask the user an input (for example):
std::string numbers;
std::cout << What is your favorite number;
std::cin >> numbers
If the user entered
1, 2, 3
How do I extract only the number "2"? I know in python, you would do something like numbers[1], but is there a same way in C++ as well?
So, "what are your favorite numbers?"
The idea is the same as in python or any other language: split the input line by the separator character, trim if you care, and finally get the element you want, if it exists.
Splitting a string by a character
Eventually, trim
Finally, you should have a vector of string, and you can get the second with v[1] or similar, checking if it exists
you can get the length of string by numbers.length().
then you can use for loop.
for(int i =0 ; i < numbers.length();i++)
{
if(numbers[i] == '2')
// do what you want you do here with 2
}
Keep in mind, your cin won't get entire "1, 2, 3" string because of whitespace. You should use getline instead of cin.
such as..
getline(cin, numbers,'\n');
To catch a line of numbers:
int main()
{
std::vector<int> numbers;
std::string line;
std::getline(std::cin, line); // First read the whole line of input
std::stringstream linestream(line); // Set up to parse the line
int number;
while(linestream >> number) { // Read a number
char x; // for the comma
linestream >> x; // remove the comma
numbers.push_back(number); // Add to the vector (array)
}
// Print the number
std::cout << "The second number is: " << numbers[1] << "\n"; // vectors are 0 indexed
}

How to retrieve the data back from ifstream [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 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.