2012-07-31 92 views
0

我怎样才能让这个程序的输出正常工作?我不知道为什么字符串数组不会存储我的值,然后在我的程序结束时输出它们。谢谢。字符串数组输出

#include <iostream> 
#include <string> 
using namespace std; 
int main() 
{ 
    int score[100], score1 = -1; 
    string word[100]; 
    do 
    { 
     score1 = score1 + 1; 
     cout << "Please enter a score (-1 to stop): "; 
     cin >> score[score1]; 
    } 
    while (score[score1] != -1); 
    { 
     for (int x = 0; x < score1; x++) 
     { 
      cout << "Enter a string: "; 
      getline(cin,word[x]); 
      cin.ignore(); 
     } 
     for (int x = 0; x < score1; x++) 
     { 
      cout << score[x] << "::" << word[x] << endl; // need output to be 88:: hello there. 
     } 
    } 

} 
+2

什么不工作?给出错误信息,预期输出,你的程序实际上做了什么... – Lanaru 2012-07-31 19:52:20

+0

请发布一些示例输入和输出值,以便我们可以看到发生了什么。 – 2012-07-31 20:00:10

+0

Theres没有错误信息。例如,输入将是15,16,17 ...你好!!,你好吗?,我很好......输出应该是15 ::你好! ..等 – user1566796 2012-07-31 20:21:23

回答

0

在第一个循环中,您在第一个值被分配之前递增“score1”。这将你的值放置在索引1开始的score []数组中。但是,在下面的“for”循环中,你开始索引为0,这意味着你的分数/字符串关联将被关闭。

+0

不,'score1'初始化为'-1',所以使用的第一个索引是0. – 2012-07-31 19:55:46

+0

Argh,我不好,你说得对。然后,一些示例输入和输出将会有所帮助。 – 2012-07-31 19:56:52

0

更换

getline(cin,word[x]); 
cin.ignore(); 

cin >> word[x]; 

,然后试图搞清楚你在哪里错了。

+0

只要我没有空间,此解决方案就可以工作。如果我尝试输入你好,那里!生病得到输入字符串:输入字符串: – user1566796 2012-07-31 20:29:58

1

我已更正您的代码。尝试类似这样的

#include <iostream> 
#include <string> 
using namespace std; 
int main() 
{ 
    int score[100], score1 = -1; 
    char word[100][100]; 
    do 
    { 
     score1++; 
     cout << "Please enter a score (-1 to stop): "; 
     cin >> score[score1]; 
    } 
    while (score[score1] != -1); 

    cin.ignore(); 

    for (int x = 0; x < score1; x++) 
    { 
     cout << "Enter a string: "; 
     cin.getline(word[x], 100); 
    } 

    for (int x = 0; x < score1; x++) 
    { 
     cout << score[x] << "::" << word[x] << endl; // need output to be 88:: hello there. 
    } 

} 

好的我做了什么?首先我删除额外的{。当我第一次看到你的代码时,我不知道在do.while中是否有do..while循环或while循环。接下来,我将字符串数组更改为char数组,只是因为我知道如何将行读取到char数组。当我需要读取字符串时,我总是使用自己的函数,但是如果您真的想使用字符串here就是很好的例子。休息很明显。 cin.ignore()是必需的,因为新行字符保留在缓冲区中,所以我们需要省略它。

编辑: 我刚刚找到更好的方法来修复您的代码。一切正常,但你需要移动cin.ignore(),并将它放在之后(score [score1]!= -1);。因为wright现在忽略了每一行的第一个字符,并且只需要在用户类型-1后忽略新行。 Fixed code.

+0

如果你解释了为什么这个工作正常,但是OP的代码没有,这将是很好的。 – 2012-07-31 20:12:36

+0

不应该是'cin.ignore(INT_MAX,'\ n')'忽略所有待处理的输入吗? – jahhaj 2012-07-31 20:15:24

+0

不,你只需要忽略用户输入-1后的'\ n'。 getline用'\ n'读取整行,因此不需要在循环中执行它 – janisz 2012-07-31 20:27:43