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

How to ensure that my program prints the supplied values, not incorrect values?

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

数据

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

And then it should work.

第二次更新:

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