我用C ++编写了一个程序,用空格键将单词与一行分开,并将这些单词显示为数组。我的代码有什么问题? [英] 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?

查看:143
本文介绍了我用C ++编写了一个程序,用空格键将单词与一行分开,并将这些单词显示为数组。我的代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我找到该程序中的错误,它通过空格键将行分隔为单词。并显示为列表。
如果单词的第一个字符为小写,则将其转换为大写。

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<<"\nList["<<a+1<<"]="<<List[a];

    return 0;
}

预期输出:

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

实际输出:

List[1]=Hi    
List[2]=ThereiXŚm    
List[3]=Buddy   


推荐答案

我建议您使用字符串,因为您已经包含了它。在这种情况下,列表并不是必需的。尝试制作一个for循环,将行分隔为单词,我认为在使用数组时应使用for循环。在for循环中,当您遍历该行时,只需添加一个if语句即可确定您是否在单词的结尾。我认为您的代码中的问题是多个循环,但是我不确定。

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<<'\n';
        } else {
            cout<<line[i];
        }

    }

    return 0;
} ```

这篇关于我用C ++编写了一个程序,用空格键将单词与一行分开,并将这些单词显示为数组。我的代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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