1

I was asked a question on an assignment about stings. The question asked: Given the declaration: char myString[16]; Which of the following statements is valid? If a statement is invalid, provide the correct syntax.

a. strcpy(myString, “Hello the world”);
b. strlen(myString);
c. myString = “Marylane”;
d. cin.getline(myString, 80);
e. cout << myString;
f. if (myString >= “Nice day”)
     cout << myString;
g. myString[6] = ‘t’;

The I have been able to compile several of these sections as follows:

/*b.*/ int len;
 len = strlen(myString);

/*c.*/ strcpy(myString, “Hello the world”);

/*f.*/ int strTest;
 strTest = strcmp(myString, "Nice day");

 if (strTest < 0)
   cout << myString << endl;
 else 
   { 
   cout << "No Dice" << endl; 
   }

I assumed 'g' would be invalid because I thought you could not use a assignment operators, but I got it to compile. Can anyone explain that?

Prometheus
  • 1,522
  • 3
  • 23
  • 41
Part_Time_Nerd
  • 994
  • 7
  • 26
  • 56
  • Why would you not be able to use the assignment operator? In this case, you are simply assigning a raw value to a memory location. – jtbandes Nov 29 '16 at 07:02
  • 2
    You can't assign to an array, but you can assign to a single element in the array (unless it is itself an array). – Some programmer dude Nov 29 '16 at 07:02
  • What would you think would be the proper way to set the seventh character in the string to a `t`? – David Schwartz Nov 29 '16 at 07:12
  • The way it is shown above makes sense to me. I just noticed in our book where it said, "Because aggregate operations, such as assignment and comparison, are not allowed on arrays, the following statement is not legal: studentName="Lisa Johnson"; " How is that different from what is above? – Part_Time_Nerd Nov 30 '16 at 04:04

2 Answers2

2

char myString[16]; is an array. myString[6] = 't'; assigns character 't' to the sixth index of that array. This is a valid operation in C++.

VLL
  • 9,634
  • 1
  • 29
  • 54
1

You are using std::string to make operations for your strings in your code, and std::string is mutable. So you can change some parts of your string with basic operations like in your assignment. I would suggest you to read either the documentation or this answer: https://stackoverflow.com/a/2916394/1867076

Also, you can find some examples to help you in here too: http://www.cplusplus.com/forum/beginner/821/

Please inform me if this not provides an answer to your question.

Community
  • 1
  • 1
Prometheus
  • 1,522
  • 3
  • 23
  • 41