Need help understanding C-string question

Hi, I had the following question on my mid-term in my intro to programming class and guessed the answer and got lucky but I still don't completely understand how the entire process works specifically the "strcpy(a, s.c_str());" part. I don't completely understand why the answer is D. atoyOTA. Thanks.

What is the output of the following program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()
{
char a[] = "AToyota!";
char temp;
string s = "AToyota";
strcpy(a, s.c_str());
for (int i = 0; i < strlen(a) / 2; i++)
{
temp = toupper(a[i]);
a[i] = a[strlen(a) ‐ i ‐ 1];
a[strlen(a) ‐ i ‐ 1] = temp;
}
cout << a;
return 0;
}


A. ATOYOTA!
B. AtoyOTA
C. atoyota
D. atoyOTA //correct answer
E. AtoyOTA
Last edited on
this is an string reversing program and toupper function converts them into capital letters since for loop has strlen(a)/2 this calculates length of string entered which is 7.since 7/2=3 considering integer part it will capitalise first 3 letters of the string which is reversed.
so it a conversion from a c string to a string or vice versa, what does strcpy(a, s.c_str()); exactly do?

suppose y="abc"
it copies the string as it is from second variable to first for ex strycpy(x,y) will copy the string "abc" in x or makes x="abc"
Oh ok, so for "strcpy(a, s.c_str());", is the string s copied onto the c string a? Also, why is there s.c_str() and not just "s" as in strcpy(a,c)? s is a string so why would it have .c_str() with it?
why is there s.c_str() and not just "s" as in strcpy(a,c)? s is a string so why would it have .c_str() with it?

strcpy is a C library function. It has no idea what a C++ string object is. That is why you have to use c_str() to return a pointer to a C compatible string..
Topic archived. No new replies allowed.