从输入中读取单词序列。使用"Quit"终止,按输入顺序打印,不要打印两次单词。

Read a sequence of words from input. Use "Quit" to terminate, print in order they were entered and don't print a word twice.

本文关键字:打印 输入 单词 两次 顺序 使用 读取 Quit 终止 单词序      更新时间:2023-10-16

如果有人能提供比我更好的代码,那就太好了,尽管工作也很糟糕。另外,我的代码有问题!!当我打印我的新数组arr时,在输出中,当有一个重复的单词时,数组的位置被跳过,并为它输出一个空白空间。

例如:

bat,
cat,
mat,
       //here the word bat is not printed again, but instead i get an empty space
rat,
quit,

也请只使用指针,数组或字符串,因为我还没有研究向量,列表,映射等。谢谢你。

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
    string word[100];
    string arr[100];
    int i=0,j,k,m,n;
    while(1)
    {
        cout<<"enter word: n";
        cin>>word[i];
        if(word[i]=="quit")  
        break;
        i++;
    } 
    for(j=i,m=0;j>=0,m<=i;m++)
    {                     
        for(k=j-1;k>=0;k--)
        {
            if(word[j] == word[k])
            goto start;                         
        }   
        arr[m]=word[j];                                                              
        start:
        j--;                                       
     }                                                 
     for(n=m;n>0;n--)
         cout<<arr[n]<<"n";                                           
     getch();
 }

修正了一点,我不想花时间去理解你的for(j=i,m=0;j>=0,m<=i;m++)循环,所以完全重写了它。

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
    string word[100];
    string arr[100];
    int wordCount = 0;
    while(1)
    {
        cout<<"enter word: n";
        cin>>word[wordCount];
        if(word[wordCount] == "quit")
        {  
            break;
        }
        ++wordCount;
    } 
    int arrCount = 0;
    for(int i = 0; i < wordCount; ++i)
    {                  
        bool found = false;   
        for (int j = 0; j < arrCount; ++j)
        {
            if (arr[j] == word[i])
            {
                found = true;
                break;
            }
        }
        if (!found)
        {
            arr[arrCount] = word;
            ++arrCount;
        }
    }                                                 
    for(int i = 0; i < arrCount; ++i)
    {
        cout<<arr[n]<<"n";
    }
    getch();
}

永远不要使用goto,如果你的老师看到了,他会很生气的