如何在C ++中使用while循环将两个字符串添加到向量中 [英] How do I keep adding two strings into vectors using while loop in C++

查看:92
本文介绍了如何在C ++中使用while循环将两个字符串添加到向量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在编写一个代码,允许用户使用其导演添加某个电影的名称,然后显示用户所写的内容。我正在使用向量,但我尝试的代码只在我写出名字和导演的名字后才显示值。此外,在两个初始输入之后,字符串不会放在一起。有关继续向向量添加值然后显示的任何帮助?下面的代码是一个构造函数Movie()。



我尝试过:



Hello, I am writing a code that allows users to add a certain movie's name with its director and then display what the user wrote. I am using vectors but the code that I tried only displays the values after I write the first name and director's name. Moreover, after the two initial inputs the strings are not put together. Any help on keep adding values to the vector then displaying? The code below is a constructor Movie().

What I have tried:

Movie() {
		cout << "Enter the film name name: " << endl;
		getline(cin, filmname);
		cout << "Enter the director's name: " << endl;
		getline(cin, director);
		full = filmname + " " + director;
		cout << "The film and director is therefore: " << full << endl;
		while (cin >> full) {
			if (full == "end") {
				break;
			}
			Film.push_back(full);
		}
		cout << "You entered the following: ";
		for (int i = 0; i < Film.size(); i++) {
			cout << Music[i] << endl;
		}
	}

推荐答案

使用cin>>完全用新输入覆盖当前的full值。

你应该将新输入存储在一个单独的字符串中并追加到完全直到输入end。
With cin >> full you are overwriting the current value of full with the new input.
You should store the new input in a separate string and append to full until "end" is typed.


语句应该在块的开头,在你获得电影细节之前,do循环可能会更好:

The while statement should be at the beginning of the block, before you get the film details, and a do loop would probably work better:
do
{
    cout << "Enter the film name name: " << endl;
    getline(cin, filmname);
    if (filmname == "end")
        break;
    cout << "Enter the director's name: " << endl;
    getline(cin, director);
    full = filmname + " " + director;
    cout << "The film and director is therefore: " << full << endl;
    Film.push_back(full);
} while (true);


这篇关于如何在C ++中使用while循环将两个字符串添加到向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆