空字符数组的初始化是否有效
Is the initialization of the empty char array valid?
int main()
{
cout<<"Enter a word"<<endl;
char word1[]={0}; //first char array initialization
cin>>word1;
cout<<"Enter another word"<<endl;
char word2[]={0}; //second char array initialization
cin>>word2;
char word3[]={0};
char word4[]={0};
int i=0;
while (word1[i]!=' ') //this converts both words to lower case by usinction tolower
{
word3[i]=char(tolower(word1[i])); //word3 and word4 stores the new arrays
word4[i]=char(tolower(word2[i]));
i++;
}
int output; //output stores the value of 0,1 or -1
output=compareString(word3,word4);
if (output==0)
{
cout<<"The two words are the same."<<endl; //if arrays are same
}
if (output==1)
{
cout<<"the 1st character of 1st word has a larger value than of 2nd word."<<endl;
}
if (output==-1)
{
cout<<"the 1st character of 2nd word has a larger value than of 1st word."<<endl;
}
return 0;
}
int compareString(char string1,char string2)
{
int size1=0; //initialize size of string1
int j=0; //string1 position initialize
while (string1[j]!=' ') //loop to determine size of string1
{
size1+=1;
j+=1;
}
int a=0; //initialize size of string2
int size2=0; //string2 position
while (string2[a]!=' ') //loop determines size of string2
{
size2+=1;
a+=1;
}
int i=0;
int k=0;
for (i=0;i<size1;i++) //loop to compare the two strings
{
if (string1[i]!=string2[i])
{
if (string1[i]>string2[i]) //comparing 1st character of string1 & string2
{
return 1;
}
else //if string2's first character is greater in value
{
return -1;
}
}
else
{
k++; //incrementing k when character of string1 matches string2 character
}
}
if (k==size1) //to cjheck if all characters of both strings are same
{
if (k==size2)
{
return 0;
}
}
}
这是一个函数,它比较两个 char 数组,如果字符彼此对应,则返回 0,如果字符串 1 的第一个字符的值大于字符串 2 的第一个字符,则返回 1,如果字符串 1 的第一个字符小于字符串 2 的第一个字符,则返回 -1。问题是当我运行它时,即使两个单词不同,输出也始终为 0,并且出现文本"单词相同"。我在主程序中是否正确初始化了这两个数组?还是存在其他问题?
此声明
char word1[]={0};
声明一个大小为 1 的数组,这意味着当您进行输入时,它将覆盖堆栈。所有其他数组也是如此。
在C++处理字符串时,强烈建议使用 std::string
!
char word1[]={0};
此行创建一个数组word1
,该数组只有一个元素,设置为 0。 使用此数组保存字符串时,除了空字符串之外,您不能保存其中的任何内容。 您在此处导致缓冲区溢出,因为您将非空字符串读入此数组,然后该字符串将写入未分配给此数组的内存的其他部分。 这是非常糟糕的。
请考虑改用std::string
来保存字符串。 它将根据需要自动调整其分配大小。
相关文章:
- 如果变量名称不跟在 char* 后面,const char* 是否有效?
- 钳制迭代器是否有效
- 检查由括号、方括号和大括号组成的一组方括号是否有效?
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 模板签名解析为 void(void) 被 GCC 拒绝;这是否有效C++?
- 我如何知道作为参数的size_t在函数中是否有效?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 此递归模板类型定义是否有效C++?
- 将 C 函数转换为 C++ 以检查数字是否有效
- 函数参数的名称与调用函数时使用的变量相同是否有效?
- 如何检查输入是否有效?
- 如何检查用户的输入是否有效以及我正在寻找的数字?
- 在函数中按值传递 unordered_map/unordered_set 是否有效? C++
- 如何检查isupper(cstr)是否有效?
- 将 std::transform 与 std::back_inserter 一起使用是否有效?
- 只需要知道我在c ++中打印模式的方式是否有效,或者有另一种方法可以有效地做到这一点
- 如何检查字符串格式在读取C++文本文件时是否有效?
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- 创建加密安全密码.并验证它是否有效