A
A
Alexander Opper2021-11-12 16:42:14
C++ / C#
Alexander Opper, 2021-11-12 16:42:14

How to output an array of characters correctly?

You need to write the entered string the other way around, it seems that you did everything right, but the problem is that instead of an array of characters, the program displays just an empty string. If I output a character individually, then everything will be fine, but I need to transfer the result to another array of characters.
Tried through the function cout, puts.
If you specify str in the argument, it will display the word entered by the user.

#include <iostream>
#include <conio.h>
#include <stdio.h>
using namespace std;

int main() {
  char str[100];
  char tmp[100];
  puts("Enter some characters: "); gets(str);
  for(int i = strlen(str), j = 0; j < strlen(str); i--, j++) {
    tmp[j] = str[i];
  }
  puts(tmp);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2021-11-12
@Unbhopper

the problem is that instead of an array of characters, the program displays just an empty string.

the program outputs an empty string because tmp is an empty string. Because it i = strlen(str)puts in i the index of the 0-terminator of str, not the last character before it. And there is no 0-terminator at the end of the tmp line now, so it puts(tmp)will print garbage after the reversed line if the initialization of i is corrected.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question