Difference between revisions of "Code Snippet: User Input-Single Line"
From Coder Merlin
Nerdofcode (talk | contribs) |
Nerdofcode (talk | contribs) m (→C) |
||
Line 37: | Line 37: | ||
char line_buffer[64]; // Declare array capable of holding 63 characters | char line_buffer[64]; // Declare array capable of holding 63 characters | ||
fgets(line_buffer,64,stdin); // Direct fgets to read from stdin with a max buffer size of 64 | fgets(line_buffer,64,stdin); // Direct fgets to read from stdin with a max buffer size of 64 | ||
printf("You | printf("You typed: %s\n",line_buffer); //Output input | ||
return 0; // Indicate a successful run to the OS | return 0; // Indicate a successful run to the OS |
Revision as of 20:07, 24 December 2018
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Reading a single line of text from the console[edit]
Note: Input read from the console is terminated with a ^D (Control-D) which indicates the end-of-file.
Swift[edit]
// Read a single line of input from the console
let line = readLine() // This will return an optional string
if line != nil { // Let's check if it's not nil, if so, it's really a string
let text = line! // Unwrap the string
print("You typed: \(text)") // Print the string
}
// Read a single line of input from the console (syntactic sugar)
if let text = readLine() {
print("You typed: \(text)")
}
Python[edit]
try:
text = input()
except:
text = ""
print("You typed: %s" %text)
C[edit]
#include <stdio.h>
int main(void){
char line_buffer[64]; // Declare array capable of holding 63 characters
fgets(line_buffer,64,stdin); // Direct fgets to read from stdin with a max buffer size of 64
printf("You typed: %s\n",line_buffer); //Output input
return 0; // Indicate a successful run to the OS
}