Code Snippet: User Input-Multi Line

From Coder Merlin
Jump to navigation Jump to search

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;
}


CoderMerlin™ proudly recommends:
HintIcon.png

Your purchase via these links helps keep  Coder Merlin™ 's orbuculum ablaze. As an Amazon Associate we earn from qualifying purchases. Thank you for your support!


Designed with pride in Silicon Valley, CA, USA