Difference between revisions of "Code Snippet: User Input-Multi Line"
From Coder Merlin
Nerdofcode (talk | contribs) |
(C++ example) |
||
Line 47: | Line 47: | ||
} | } | ||
</syntaxhighlight> | |||
== C++ == | |||
<syntaxhighlight lang="c++"> | |||
#include <iostream> | |||
#include <string> | |||
int main() { | |||
std::string line; | |||
while (!std::cin.eof()) { | |||
std::getline(std::cin, line); | |||
if (!std::cin.fail()) { | |||
std::cout << "You typed: " << line; | |||
} | |||
} | |||
return 0; | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 10:12, 24 August 2020
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Reading multiple lines 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 multiple lines from the console until end-of-file
var line : String?
repeat {
line = readLine() // Read a single line of input from the console
if let text = line { // Let's check if it's not nil, if so, it's really a string
print("You typed: \(text)") // Print the string
}
} while line != nil // Continue until end-of-file
Python[edit]
text = ""
while text is not None:
try:
text = input()
except:
text = None
continue
print("You typed: %s" %text)
C[edit]
#include <stdio.h>
#include <string.h>
int main(void){
char line_buffer[64]; // Declare character array, capable of holding 63 characters
do {
memset(line_buffer,0,64); // Reset value of line_buffer
fgets(line_buffer,64,stdin); // Save input from stdin to line_buffer
printf("You typed: %s\n",line_buffer);
} while(strlen(line_buffer) != 0); // Verify that user didn't provide EOF
return 0; // Indicate successful run to OS
}
C++[edit]
#include <iostream>
#include <string>
int main() {
std::string line;
while (!std::cin.eof()) {
std::getline(std::cin, line);
if (!std::cin.fail()) {
std::cout << "You typed: " << line;
}
}
return 0;
}