简单程序省略了第一个字符

First char omitted by simple programm

本文关键字:第一个 字符 程序省 简单      更新时间:2023-10-16

任务是cin>>....,只取字母,将大写字母改为小写字母,并用小写字母重写行。我不明白为什么我的代码忽略了输入的第一个字母。

#include <iostream>
#include <cctype>
using namespace std;
int main()
{
    char ch;
    cin >> ch;
    while (ch != '@'){
        if (cin.get(ch))
        {
            if (isalpha(ch)){
                if (isupper(ch)){
                    cout <<(char)tolower(ch);
                }
                else
                    cout << ch;
            }
            if (ch == 'n')
                cout << "nNie zakonczyles ciagu znakiem @" << endl;
        }
        else{
            cin.clear();
        }
    }
}

因为循环使用cin.get(ch)来获取要打印的字符,但实际上第一个字符是用cin >> ch读取的;然后将结果丢弃。

您可能想要摆脱cin>>ch;指令并将ch初始化为与'@'不同的值,或者将循环转换为do-while循环,类似于:

char ch;
do
{
    if (cin.get(ch))
    {
       /* Do what is needed */
    }
}
while (ch != '@')
cin >> ch;  <- read first letter
while (ch != '@'){
    if (cin.get(ch)) <- read next letter which tosses out the first letter

设置ch为某个值,然后去掉cin >> ch;

因为在cin >> ch;之后是cin.get(ch)