'How to ensure that my program prints the supplied values, not incorrect values?
Why my program is printing incorrect values, not the supplied values? Any help would be much appreciated.
Data
title1=q, year1=1, title2=w, year2=2
Code
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int getnumber ();
struct movies_t {
string title;
int year;
};
void printmovie (movies_t films);
int main ()
{
int z=getnumber ();
cout << "You will have to provide data for " << z << " films.\n";
//movies_t films [z];
vector<movies_t> films(z);
string mystr;
int n;
for (n=0; n<z; n++)
{
cout << "Enter title: ";
getline (cin,films[n].title);
cin.ignore();
cout << "Enter year: ";
getline (cin,mystr);
cin.ignore();
stringstream(mystr) >> films[n].year;
}
cout << "\nYou have entered these movies:\n";
for (n=0; n<z; n++)
printmovie (films[n]);
return 0;
}
void printmovie (movies_t films)
{
movies_t * pmovie;
pmovie = &films;
cout << pmovie->title;
cout << " (" << films.year << ")\n";
}
int getnumber ()
{
int i;
cout << "Please enter number of films: ";
cin >> i;
return i;
}
Output (obtained; incorrect)
Please enter number of films: 2
You will have to provide data for 2 films.
Enter title: q
Enter year: 1
Enter title: w
Enter year: 2
You have entered these movies:
(0)
(0)
Output (desired)
Please enter number of films: 2
You will have to provide data for 2 films.
Enter title: q
Enter year: 1
Enter title: w
Enter year: 2
You have entered these movies:
q (1)
w (2)
Solution 1:[1]
Make a function that gets the value after = in each token.
string getValue(string field) {
auto pos = field.find('=');
return field.substr(pos + 1, field.find(',') - pos - 1);
}
Then all you need to do is:
for (n = 0; n < z; n++) {
string title, year;
assert(cin >> title >> year);
movies_t movie = {getValue(title), stoi(getValue(year))};
films.push_back(movie);
}
To use assert you need #include <cassert> at the top.
Update:
You need to ignore spaces, so add this to your program:
struct ctype_ : std::ctype<char>
{
static mask* make_table()
{
const mask* table = classic_table();
static std::vector<mask> v(table, table + table_size);
v[' '] &= ~space;
v[','] |= space;
return &v[0];
}
ctype_() : std::ctype<char>(make_table()) { }
};
And then do this just before the for loop:
cin.imbue(std::locale(cin.getloc(), new ctype_));
2nd update:
for (n = 0; n < z; n++) {
string title, year;
cout << "Enter title: ";
assert(cin >> title);
cout << "Enter year: ";
assert(cin >> year);
movies_t movie = {getValue(title), stoi(getValue(year))};
films[n] = movie;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
