7 years ago.

Having problems using cin to enter strings with Mbed, why!

Sorry, I am a only just getting to grips with this, Im new to the Mbed. This simple program is not working for me and I don't understand why.

output is directed to Terminal on the Mac using.. screen /dev/tty.usbmodem*

 // cin with strings

 #include "mbed.h"
 #include <iostream>
 #include <string>

 using namespace std;
 
  int main ()
  {
   string mystr;
   cout << "What's your name? ";
   getline (cin, mystr);
   cout << "Hello " << mystr << ".\n";
   cout << "What is your favorite team? ";
   getline (cin, mystr);
   cout << "I like " << mystr << " too!\n";
   return 0;
 }

Thanks for any help.

Comment on this question

3 Answers

7 years ago.

In principle it works for me under windows with teraterm. How doesnt it work for you? If it doesnt react when you type an answer to the first question, you probably got settings in your terminal program which prevents the getline command from noticing a newline, so then change your terminal settings. And for some reason the answer to second question doesnt come for me unless I add another getline in the end.

However more important: Usage of strings results in massive memory usage. This program uses almost 8kB ram, which doesnt sound much, until you realise that is 25% of your ram. Using char-arrays is alot more efficient. For example the next program does the same as yours (granted scanf is kinda suspectible to buffer-overflows, but I dont think thats too important here).

#include "mbed.h"


int main () { 
    char response[20];
    printf("What is your name? ");
    scanf("%20s", response);
    printf("\nHello %s!\n",response);
    printf("What is your favorite team? ");
    scanf("%20s" , response);
    printf("\nI like %s too!\n",response);
    while(1);
    }

This uses a negligible amount of ram.

7 years ago.

Thanks Erik, Im very grateful for the reply. The information on 'strings' is extremely valuable and I will take your advice which will solve my problem, again many thanks.

In respect to the use of cin for the first and second questions in the example. I believe there is a bug in some part of the compiler. I get exactly the same response as you indicated that you get. The first question works correctly every time, the second cin within a function either hangs or exits the function missing the last part of the function. So I believe this is where the problem lies. I have tried multiple programs to find the bug (the example I supplied is from a published program) all with the same result. Any thoughts?

7 years ago.

Good chance it is just what you said, a bug. The cin, cout is mainly supported for completeness, but because of its inefficiency it isnt used often, so bugs arent found. Maybe an mbed dev sees this and can have a look at it.