c++ char type output

Asked 2 years ago, Updated 2 years ago, 56 views

I got 123456 input I'm trying to print out 321654 What's wrong with my form??

int main() {
    int t = 0;
    char str1[4];
    char str2[4];
    cin >> str1 >> str2;
    char str1copy[4] = { 0 };
    char str2copy[4] = { 0 };

    for (int i = 2; i >= 0; i--) {
        str1[i] = str1copy[t];
        t++;
    }
    for (int a = 2; a >= 0; {
        str2[a] = str2copy[t];
        t++;
    }
    str1copy[3] = 0; str2copy[3] = 0;
    cout << str1copy[t]<< str2copy[t];

}

array char c++

2022-09-20 16:01

1 Answers

Four places are wrong.

First of all, the second for loop itself is a typo.

 for (int a = 2; a >= 0; {

Please change the line above as below.

for (int a = 2; a >= 0; a--) {

The second problem is that you're trying to copy the values of str1 and str2 to str1copy, str2copy, so the left and right sides of the sentence below are reversed.

str1[i] = str1copy[t];
str2[a] = str2copy[t];

Change the sentence above as below.

str1copy[t]=str1[i];
str2copy[t]=str2[a];

The third problem is that we're using the increased t in the first for loop as it is in the second for loop. You must initialize to t=0; before the second for loop starts.

The last wrong place is where the cout is. To output a string of char-type arrays, you must specify only the name of the array.

cout << str1copy[t]<< str2copy[t];

Change the sentence above as below.

cout << str1copy<<' '<< str2copy;

Below is the revised full code.

#include <iostream>

using namespace std;

int main()
{
    int t = 0;
    char str1[4];
    char str2[4];
    cin >> str1 >> str2;
    char str1copy[4] = { 0 };
    char str2copy[4] = { 0 };

    for (int i = 2; i >= 0; i--) {
        str1copy[t] = str1[i];
        t++;
    }
    t = 0;
    for (int a = 2; a >= 0; a--) {
        str2copy[t] = str2[a];
        t++;
    }
    str1copy[3] = 0;
    str2copy[3] = 0;
    cout << str1copy << ' ' << str2copy;

    return 0;
}

Results

I think it's usually salty like below.

#include <iostream>

using namespace std;

int main()
{
    char str1[20] = { 0, };
    char str2[20] = { 0, };
    char str1_copy[20] = { 0, };
    char str2_copy[20] = { 0, };

    cin >> str1 >> str2;

    int str1_len = strlen(str1);
    int str2_len = strlen(str2);

    for (int i = 0; i < str1_len; ++i)
        str1_copy[i] = str1[str1_len - 1 - i];

    for (int i = 0; i < str2_len; ++i)
        str2_copy[i] = str2[str2_len - 1 - i];

    cout << str1_copy << ' ' << str2_copy << '\n';

    return 0;
}

Results


2022-09-20 16:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.