如何确保我的程序打印提供的值,而不是不正确的值?



为什么我的程序打印不正确的值,而不是提供的值?如有任何帮助,不胜感激。

title1=q, year1=1, title2=w, year2=2

#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;
}

输出(获得;不正确的)

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)

输出(期望)

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) 

编写一个函数,获取每个令牌中=后面的值

string getValue(string field) {
auto pos = field.find('=');
return field.substr(pos + 1, field.find(',') - pos - 1);
}

那么你所需要做的就是:

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);
}

要使用assert,你需要#include <cassert>在顶部。

更新:

你需要忽略空格,所以把这个添加到你的程序中:

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()) { }
};

然后在for循环之前执行此操作:

cin.imbue(std::locale(cin.getloc(), new ctype_));

然后它应该工作。

2日更新:

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;
}

最新更新