Thread: how do I get a single character from a text string?

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    2

    how do I get a single character from a text string?

    I would like to obtain the first character from a text string and assign it to a variable. I tried to create an ifstream object to open a text file and using its get() function but was unsuccessful.

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Show the code where you tried to open and read from the file.

    Jim

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    2
    Code:
    char letter
    
    ifstream reader("poem.txt");
    if (!reader)
    {
      cout << "Error opening input file" << endl;
     return -1;
    }
    else
      reader.get(letter);
      cout << letter;
    
    reader.close();

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Other than missing a semicolon, a main function and include files your snippet looks correct.

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to take a SINGLE UNKOWN character from a string
    By stmty9 in forum C Programming
    Replies: 8
    Last Post: 12-01-2010, 10:49 PM
  2. get single character from string
    By deltaxfx in forum C Programming
    Replies: 7
    Last Post: 01-06-2006, 01:21 PM
  3. Deleting a single character from a string
    By caduardo21 in forum C Programming
    Replies: 10
    Last Post: 02-16-2005, 06:51 PM
  4. Printing single character from a string
    By TJJ in forum C Programming
    Replies: 4
    Last Post: 11-05-2003, 06:25 PM
  5. How to strcopy a single character from a string
    By Stuu in forum C++ Programming
    Replies: 8
    Last Post: 04-18-2002, 01:45 AM