Вы должны действительно перейти на современный компилятор. Доступно много бесплатных.
#include <iostream.h> // non-standard header file
#include <string.h> // not recommended - it brings its functions into the global namespace
void main() { // main must return "int"
int i, n;
char* x = "Alice"; // illegal, must be const char*
n = strlen(x);
*x = x[n]; // illegal copy of the terminating \0 to the first const char
for(i = 0; i <= n; i++) { // <= includes the terminating \0
cout << x; // will print: "", "lice", "ice", "ce", "e", ""
// since you move x forward below
x++;
}
cout << endl << x; // x is now pointing after the \0, undefined behaviour
}
Если вы хотите печатать буквы по одной (используя вашу текущую программу в качестве основы), используя стандарт C ++:
#include <iostream>
#include <cstring>
int main() {
const char* x = "Alice";
size_t n = std::strlen(x);
for(size_t i = 0; i < n; ++i, ++x) {
std::cout << *x; // *x to dereferece x to get the char it's pointing at
}
std::cout << "\n"; // std::endl is overkill, no need to flush
}
Что strlen
делает, это ищет первый \0
символ и подсчитывает, сколько времени ему пришлось искать. Вам действительно не нужно делать это здесь, так как вы проходите все символы (шагая x
) самостоятельно. Иллюстрация:
#include <iostream>
int main() {
const char* x = "Alice";
size_t n = 0;
while(*x != '\0') {
std::cout << *x;
++x;
++n;
}
std::cout << "\nThe string was " << n << " characters long\n";
}