Thread: Reading Line From a .txt File Problems

  1. #1
    Registered User
    Join Date
    Aug 2013
    Posts
    40

    Reading Line From a .txt File Problems

    Hey I'm trying to read the first line from a .txt file and print it to the terminal with the bellow code.

    Code:
    char pass[40];
    FILE *login = fopen("test.txt", "r");
    fgets(pass, 40, login);
    printf("%s\n", pass);
    I set the char size to 40 because that was the maximum size allowed when I printed to line to the file. The problem I'm having is there seems to be a bunch of blank space and a new line at the end of the string. I tried to remove it with the bellow for loop but when I do I get a bunch of junk at the end that shows up a "?" characters in my terminal. I have tried checking for new lines and not "0" in the for loop but I still get junk left at the end of the string showing as "?".

    Code:
    char passhold[40];
    for(int i = 0; pass[i] != 0; i++){
        passhold[i] = pass[i];
      }
      printf("%s\n", passhold);
    I cant work out how to fix it. I just want to read the first line and not have blank space at the end of the string.
    Last edited by Xecutive; 11-03-2016 at 08:29 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    fgets will store the newline from the input at the end of the string if there is space for it, so that is to be expected and easily removed by a variety of ways, e.g.,
    Code:
    pass[strcspn(pass, "\r\n")] = '\0';
    But, are you trying to remove other whitespace at the end of the string? As in, is the whitespace expected or unexpected?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Aug 2013
    Posts
    40
    Thanks that fixed it

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems while reading a file line by line
    By tinchi in forum C Programming
    Replies: 9
    Last Post: 08-17-2014, 12:10 PM
  2. Replies: 6
    Last Post: 06-07-2012, 02:50 AM
  3. Replies: 7
    Last Post: 12-13-2010, 02:13 PM
  4. reading words line by line from a file
    By -EquinoX- in forum C Programming
    Replies: 3
    Last Post: 05-04-2008, 12:34 AM
  5. Reading Input from a file, line-by-line
    By Acolyte in forum C Programming
    Replies: 8
    Last Post: 09-30-2007, 01:03 PM

Tags for this Thread