【问题标题】:how to get character array to print out in one line and not multiple in c++?如何让字符数组在一行中打印出来,而不是在 C++ 中打印多个?
【发布时间】:2020-10-08 00:00:42
【问题描述】:

如何在 C++ 中打印出字符数组 (msg)?我的输出打印了我在不同行上加密的单词,而不仅仅是一行。此外,“输入一行文本或'完成'”最终会重复。我假设它是因为单词之间的空格。我该如何解决?任何建议都会有所帮助!

int main()
{
    ofstream outputFile;
    string fileName; //initiate variables
    char msg[100]; 
    int i;
    std::cout<< "Enter file name to encrypt: "; //get file name from user
    std::cin >> fileName; //save file name 
    outputFile.open(fileName);
    while(true){
    std::cout<< "Enter a line of text or '" << "done" << "' to quit: "; //get line of text from user
    std::cin>> msg; //send line of text to message array 
        if (msg[0] == 'd' && msg[1] == 'o' && msg[2] == 'n' && msg[3] == 'e'){//check if done is input
            break; //if done is entered, break program
        }
        else{
            for(i = 0; (i < 100 && msg[i] != '\0'); i++){ //loops thru encrypting each letter
                msg[i] = msg[i] + 1; //encrypt text 
            }
            outputFile << msg << endl; //send encrypted string/message to file from user
            std::cout << "Encrypted message: " << msg << endl; //print encrypted text to screen
        }
   }
    outputFile.close(); //close file
    return 0;
}

【问题讨论】:

  • 你为什么使用char的数组而不是std::string?文件名为 string 的事实表明您知道 C++ 样式的字符串。
  • 对于 break:将 AND &amp;&amp; 替换为 OR || !!
  • 另外,请举个简单输入错误输出的例子
  • @Damien 您建议对以'd' 开头的每个单词进行打断,第二个字母为'o' 987654330@ 作为其第三个字母'e' 作为其第四个? &amp;&amp; 的使用对我来说看起来是正确的(但它缺少对第五个字符 '\0' 的检查)。
  • @JaMiT 对。抱歉,我读得太快了。

标签: c++ arrays loops printing char


【解决方案1】:

您的代码使用operator&gt;&gt; 来获取用户输入。这是一个基于单词的格式化输入功能。它跳过前导空白,然后提取一系列非空白字符。也就是说,它提取输入的下一个单词。得到下一个单词后,处理它,开始新的输出行,提示用户输入更多内容,然后重复。当每行有多个单词时,计算机不会等待更多输入(尽管有提示),您会看到您描述的输出。

由于您正在寻找一行输入,您应该使用一种 API,该 API 获取整个 输入,而不是一个单词。准备好这个 API 的惊人名称了吗?它被称为getline(),或者更准确地说是std::istream::getline,因为你被困在使用字符数组而不是字符串。

std::cin.getline(msg, 100);

使用std::string 不会改变结果,但它会让我更容易找到文档。 version of operator&gt;&gt; for strings 也是基于单词的。字符串的取行 API 是一个免费函数,std::getline


您的一项测试的建议输入:

Done
DONE
donegal is in Ireland
done?
done!
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 2022-01-16
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多