Code Snippet: User Input-Multi Line

From Coder Merlin
Revision as of 10:12, 24 August 2020 by Yarsenius (talk | contribs) (C++ example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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;
}