Write a loop that reads c-strings from standard input where the c-string is either "land", "air", or "water". The loop terminates when "xxxxx" (five x characters ) is read in. Other strings are ignored. After the loop, your code should print out 3 lines: the first consisting of the string "land:" followed by the number of "land" strings read in, the second consisting of the string "air:" followed by the number of "air" strings read in, and the third consisting of the string "water:" followed by the number of "water" strings read in. Each of these should be printed on a separate line. Assume that the maximum length of a string is 8.

Respuesta :

Answer:

I am writing a C++ code.        

#include <iostream> // for input output functions

using namespace std; // identifies objects like cin cout

int main() { //start of main() function body

string c_string; // stores the string entered by user from land water or air

int land=0; // contains the number of times land string is read in

int air=0; //contains the number of times air string is read in

int water = 0; //contains the number of times water string is read in

cin>>c_string; //reads the string entered by user from air water or land

/*while loop continues to execute until user enters xxxxx or maximum length of a string exceeds 8 */

while(c_string!= "xxxxx" && c_string.length()<=8) {

if(c_string=="land"){ // if string entered by user is land

land = land + 1;} //counts and increments each occurrence of land string by 1

else if(c_string=="air"){// if string entered by user is air

air = air + 1;}// counts and increments each occurrence of string air by 1

else if(c_string=="water"){// if string entered by user is water

water = water + 1;}//counts and increments each occurrence of air by 1

cin>>c_string;}

/* keeps reading the string entered by user from land air or water, until the loop breaks after the user enters xxxxx or user enters a string whose length is greater than 8 */

//prints the number of times land, air and water are read in

cout << "land:"<<land;

cout << endl<<"air:"<<air;

cout << endl<< "water:"<<water; }                      

                                                                                     

Explanation:

Everything is well explained in the comments above.

The program prompts the user to input strings. These strings are either land air or water. The while loop continues to read the input strings until user enters xxxxx or the string entered by user exceeds the length 8. Both these terminating conditions are added in the while loop. After the loop terminates, the number of times land, air and water strings are read is displayed on the output screen. Any other string entered by user other than these 3 is ignored. The program along with the output is attached.

Ver imagen mahamnasir
Ver imagen mahamnasir