我正在为我正在做的初学C++类做一些编码。在课堂上,我们必须接受另一名学生提交的代码并修复他们创建的错误。代码如下:空终止符 1?
#include <iostream>
using namespace std;
int countChars(char *, char); // Function prototype
int main()
{
const int SIZE = 51; // Array size
char userString[SIZE]; // To hold a string
char letter; // The character to count
// Get a string from the user.
cout << "Enter a string (up to 50 characters): ";
cin.getline(userString, SIZE);
// Get a character to count occurrences of within the string.
cout << "Enter a character and I will tell you how many\n";
cout << "times it appears in the string: ";
cin >> letter;
// Display the number of times the character appears.
cout << letter << " appears ";
cout << countChars(userString, letter) << " times.\n";
return 0;
}
int countChars(char *strPtr, char ch)
{
int times = 0; // Number of times ch appears in the string
// Step through the string counting occurrences of ch.
while (*strPtr != '\0')// ***** There was a one placed inside the null operator, however, this is not a syntax error, but rather just incorrect.
{
if (*strPtr == ch) // If the current character equals ch...
times++; // ... increment the counter
strPtr++; // Go to the next char in the string.
}
return times;
}
学生改变了这样的功能,它已空终止为\10
,这并没有引起编译也不运行时错误。玩过之后,我发现它也可能是\1
并且仍然有效。这怎么可能。我是一个完全noob,所以我很抱歉如果这是一个愚蠢的问题,但我认为这是一个布尔运算符,1是真的,0是错误的。问题是为什么\10
和\1
将作为空终止符。先谢谢你!
'\ number'指转义序列编写由数字代码的象征,就像'\ xnumber'不一样的,但现在你在十六进制指定它。在语法方面,除了只有''\ 0'(在字符串外部也可以表示为'\ x00''或者甚至只是'0')时,这里没有任何错误是一个有效的空终止符。 – Havenard
请注意''\ 1''和其他数字不“仍然有效”。该程序要么有运行时错误,要么有幸运。幸运的是,我的意思是你的'while'循环不断读取数组的末尾,并进入具有不可预知值的内存中。这种语言不会阻止你编写这样的代码,但这就是所谓的“未定义的行为”。什么事情都可能发生。例如,你可能很幸运,并且恰好在下一个位置有一个值为'1'的字节,并且你的程序看起来工作正常。或者没有和你的程序永远循环。或者是其他东西。它没有定义。 – Adam