Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

algorithm - I have made a program in C++ to separate words from a line by spacebar and display those words as an array. What's wrong in my code?

Please help me to find a bug in this program.It separates a line into words by spacebar. And display as a list. If the first char of a word is in lower case, it is converted to uppercase.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    char line[30]="Hi there buddy",List[10][20];
    unsigned int i=0,List_pos=0,no;
    int first=0,last;

    while(i!=sizeof(line)+1)
    {
        if(line[i]==' ' or i==sizeof(line))
        {
            last=i;
            no=0;
            for(int j=first;j<last;++j)
            {
                if(no==0)
                    List[List_pos][no]=toupper(line[j]);
                else
                    List[List_pos][no]=line[j];
                ++no;
            }
            ++List_pos;
            first=last+1;
        }
    ++i;
    }

    for(unsigned int a=0;a<List_pos;++a)
        cout<<"
List["<<a+1<<"]="<<List[a];

    return 0;
}

Expected Output:

List[1]=Hi    
List[2]=There    
List[3]=Buddy    

Actual Output:

List[1]=Hi    
List[2]=ThereiX?m    
List[3]=Buddy   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suggest you use a string, as you already included it. And 'List is not really necessary in this situation. Try making a single for loop where you separate your line into words, in my opinion when you work with arrays you should use for loops. In your for loop, as you go through the line, you could just add a if statement which determines whether you're at the end of a word or not. I think the problem in your code is the multiple loops but I am not sure of it.

I provide you a code which works. Just adapt it to your display requirements and you will be fine

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string line = "Hi there buddy";

    for (int i = 0; i < line.size(); i++) {
        if (line[i] == ' ') {
            line[i + 1] = toupper(line[i+1]);
            cout<<'
';
        } else {
            cout<<line[i];
        }

    }

    return 0;
} ```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...