鍍金池/ 問答/C++/ C++ 怎么在循環(huán)給字符數(shù)組賦值?

C++ 怎么在循環(huán)給字符數(shù)組賦值?

如果是在循環(huán)中給字符變量賦值,可以這樣:

#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;
}

這段代碼的效果是用戶可以一直輸入字符,直到輸入'.'為止,中間不論輸入空格或回車都可以繼續(xù)。
如果想把上面的字符變量改為字符數(shù)組,也用類似簡單的代碼,該怎么實現(xiàn)?
自己寫了下,但覺得有點復雜了,還用了嵌套循環(huán),請教怎么能更簡單?

#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;
}
回答
編輯回答
撥弦
#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;
}
2017年3月6日 05:55