C++ 怎么在循环给字符数组赋值?

如果是在循环中给字符变量赋值,可以这样:

#include <iostream>
int main()
{
    using namespace std;
    char ch;
    cout << "Type, and I shall repeat.\n";
    cin.get(ch);
    while(ch != '.')
    {
        if(ch == '\n')
            cout << ch;
        else
            cout << ++ch;
        cin.get(ch);
    }
    cout << "\nPlease excuse the slight confusion.\n";
    return 0;
}

这段代码的效果是用户可以一直输入字符,直到输入'.'为止,中间不论输入空格或回车都可以继续。
如果想把上面的字符变量改为字符数组,也用类似简单的代码,该怎么实现?
自己写了下,但觉得有点复杂了,还用了嵌套循环,请教怎么能更简单?

#include <iostream>
const int Asize = 20;
int main()
{
    using namespace std;
    char line[Asize];
    cout << "Type, and I shall repeat.\n";
    int count = 0;
    while(count == 0)
    {     
        cin.getline(line, Asize);          
        for(int i = 0; line[i] != '\0'; i++)
        {
            if(line[i] == '\n')
                cout << line[i];
            else 
            {
                if(line[i] == '.')
                    count++;
                cout << ++line[i];
            }
        }
    }
    cout << "\nPlease excuse the slight confusion.\n";
    return 0;
}
阅读 7.3k
2 个回答
新手上路,请多包涵
#include <iostream>
#include <string>

const int Asize = 20;
int main()
{
    using namespace std;
    char line[Asize];
    cout << "Type, and I shall repeat.\n";

    int idx=0;
    char temp{};
    do{
        cin.get(temp);
        line[idx++] = temp;
        if(idx==Asize-1){
            idx=0;
        }
    }while(temp!='.');

    cout<<string(line);

    cout << "\nPlease excuse the slight confusion.\n";
    return 0;
}

嵌套循环你在想啥呢铁子?

#include <iostream>
using namespace std;

int main()
{
    int ch;
    char ch_array[100];
    size_t i = 0;
    while ((ch = cin.get()) && i <100 && ch!='.')  
    {
        ch_array[i] = static_cast<char>(ch);
        i++;
    }
    
    return 0;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题