【问题标题】:How to uppercase a char array c++如何大写char数组c ++
【发布时间】:2014-02-20 20:30:51
【问题描述】:

大家好,

我在互联网上看到了很多关于此的帖子,但我仍然不明白如何准确地做到这一点。出于某种原因,我只能将我的 char 数组大写,直到有空格...

    #include "stdafx.h"
    #include <iostream>
    #include <string>


    std::string caps (char[]);


    int main() { 
        const int MAXLEN = 256;     
        char chaine[ MAXLEN ] = "";  

        //Here i am inputting my list of char into my array
        std::cout << "Chaîne ? ";
        std::cin >> chaine; 

        //Calling my caps function
        caps( chaine );

        // results
        std::cout << "Résultat: " << chaine << std::endl;

        _gettch();
        return 0;


    }


    std::string caps (char chaine []){


    std::string check=chaine;

    for (int i=0; i<=check.length(); i++){  //I added check.length() because it's the only way I know to check for the length of the array


    chaine[i]=toupper(chaine[i]);

    }

    return chaine;

    }

假设我写“Hey you”,输出将是“HEY”,仅此而已。我很困惑。感谢您的帮助!

【问题讨论】:

  • 那是因为std::cin &gt;&gt; wtv; 停在空白处。你应该使用getline
  • 看看std::cin &gt;&gt; chaine;之后的chaine有什么。那会给你一个答案。附:至少你可以使用gets 或者它的类似物。
  • 或使用std::noskipws
  • @James:这是一个常见的误解。 std::noskipws is only for skipping leading whitespaces 而不是介于两者之间的。
  • @legends2k 我不知道! getline 是的,谢谢你告诉我。

标签: c++ arrays size converter


【解决方案1】:

将您的输入接收更改为:

    std::string chaine;
    std::cout << "Chaîne ? ";
    std::getline(std::cin, chaine);

    caps(chaine);             // <-- pass the name by const reference

这将在不跳过空格的情况下工作。现在您有了一个std::string,而不是在caps 中创建另一个字符串,而是通过引用传递输入,即将std::string caps (char chaine []) 更改为std::string caps (const std::string &amp;chaine)

【讨论】:

    猜你喜欢
    • 2018-04-14
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多