为什么它不接受超过2个字符?

时间:2013-07-19 04:45:45

标签: c++

我有以下函数来计算句子中的字符数

// A function to get a length of any sentence.
int length(char *str){
    int size = 0;
    while(str[size] != '\0'){
    size++;
    }
  return size;
}


int main(){
    char *name = new char;
    int cnt = 0;
    cin.getline(name, length(name));

    cout << length(name) << endl;

  return 0;
}

但是当输入一个句子并得到它的长度时,我发现句子的长度只有2个字符。

为什么会这样?

3 个答案:

答案 0 :(得分:4)

此:

char *name = new char;

ONE 字符分配空间。

你更喜欢像

这样的东西
char buf[0x100];
cin.getline(buf, sizeof(buf));

代替。 (你真的不需要动态内存分配,逻辑有缺陷 - 你事先不知道输入的长度,所以length(name)作为cin::getline()的参数没有意义。)

啊,通常警告:为什么不std::string

std::string str;
std::getline(std::cin, str);

答案 1 :(得分:4)

问题在于:

char *name = new char;

你只分配1 char,如果你想在其中存储大于1个字符的东西,这是不够的(更不用说你需要另一个用于null终结符)。

而是尝试这样的事情:

char* name = new char[64];  // Be careful. Storing more than 64 characters will lead you to more or less the same error
cin.getline(name, 64);
...
delete[] name;  // Be sure to delete[] name

更好:

char name[64]; // Again, be careful to not store more than 64 characters
cin.getline(name, 64);
...

最佳:

std::string name;  // The sane way to use strings
std::getline(std::cin, name);

<小时/> 的更新: 如果您想使用std::string获取字符串的长度,可以使用std::string::size()

std::cout << name.size() << std::endl;

答案 2 :(得分:0)

当你打电话给length并开始阅读“随机”记忆位置时,你从主要的第3行开始“处于未定义行为的境界”。这可能就是你的意思

#include <iostream>

using namespace std;

int main(){
    char name[100];
    cin.getline(name, sizeof name );

    cout << sizeof name << ": " << name << endl;

  return 0;
}