Arm Mbed OS support forum

Serial communication - how to save keyboard input from terminal to a variable

Hi, I’m very new to programming in general, so please bear with me if this is very basic.

How can I save a string of characters input through the terminal (I use PuTTY) into a variable in my program?

For example I want to make it so I have

string name;

int main()
{
 printf("What is your name?");
// code to read input and save it to "name"
printf("Your name is %s", name);
}

EDIT:
So I’ve been doing some digging and finally found something that I think will help me with what I want to achieve.
This post topic helpful:
https://os.mbed.com/questions/85553/Receive-a-string-serial-communication/

Hi,

for that simple you can use the scanf function.

click for example
#include "mbed.h"
#include <string>

string name;

int main(){
    printf("What is your name?");
    // code to read input and save it to "name"
    scanf("%s", (char *)(name.c_str()));
    printf("Your name is %s\n", name.c_str());
}

If you want to use some of Mbed APIs, then check the documentation for BufferedSerial or UnbufferedSerial .

BR, Jan

1 Like

Thanks!

This is just what I needed!