C read word from line

I was wondering if there was a way to read all of the «words» from a line of text.

the line will look like this: R,4567890,Dwyer,Barb,CSCE 423,CSCE 486

Is there a way to use the comma as a delimiter to parse this line into an array or something?

asked Sep 27, 2009 at 17:18

cskwrd's user avatar

1

Yes, use std::getline and stringstreams.

std::string str = "R,4567890,Dwyer,Barb,CSCE 423,CSCE 486";

std::istringstream iss(str);
std::vector<std::string> words;

while (std::getline(iss, str, ','))
  words.push_back(str);

answered Sep 27, 2009 at 17:23

hrnt's user avatar

hrnthrnt

9,8522 gold badges30 silver badges38 bronze badges

1

//#include sstream with angular braces in header files 

std::string str = "R,4567890,Dwyer,Barb,CSCE 423,CSCE 486";

std::istringstream iss(str,istringstream:in);

vector<std::string> words;

while (std::getline(iss, str, ','))
  words.push_back(str);

takrl's user avatar

takrl

6,3683 gold badges61 silver badges69 bronze badges

answered Jun 27, 2011 at 6:44

Ravindra's user avatar

C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write an operating system. The main features of the C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like operating systems or compiler development. This article focuses on how to take a character, a string, and a sentence as input in C.

Reading a Character in C

Problem Statement#1: Write a C program to read a single character as input in C.

Syntax-

scanf("%c", &charVariable);

Approach-

  1. scanf() needs to know the memory location of a variable in order to store the input from the user.
  2. So, the ampersand will be used in front of the variable (here ch) to know the address of a variable.
  3. Here using %c format specifier, the compiler can understand that character type of data is in a variable when taking input using the scanf() function

C

#include <stdio.h>

int main()

{

    char ch;

    scanf("%c", &ch);

    printf("Output : %c", ch);

    return 0;

}

Read character

Reading a Word in C

Problem Statement#2: Write a C program to read words as input from the user.

Syntax-

scanf("%s", stringvariable);

Approach-

  1. First, initialize the char array of size ( greater than are equal to the length of word).
  2. Then, use %s format specifier to take the string using the scanf() function.

C

#include <stdio.h>

int main()

{

    char word[100];

    scanf("%s", word);

    printf("Output : %s", word);

    return 0;

}

Read word

Note:  
An array name itself indicates its address. word == &word[0], these are both the same.It’s because the variable name word points to the first element of the array. So, there is no need to mention ampersand in scanf().

Reading a Sentence in C

Problem Statement#3: Write a C program to read sentences as input from the user.

Method 1-

  1. scanf() doesn’t store the white space character in a string variable.
  2. It only reads characters other than white spaces and stores them in the specified character array until it encounters a white-space character.

Syntax-

scanf("%[^n]s", sen)

C

#include <stdio.h>

int main()

{

    char sen[100];

    scanf("%[^n]s", sen);

    printf("Output : %s", sen);

    return 0;

}

Read scentence

scanf(“%[^n]s”, sen) means to read a string including spaces until the next line is received or to read string until line break i.e. n is encountered and store it on an array named “sen”.

  1. Here, %[ ] is the scanset specifier.
  2. scanf will process only those characters which are part of scanset.
  3. If the first character of the scanset is ‘^’, then the specifier will stop reading after the first occurrence of that character.
  4. ^n  stands for taking input until a newline isn’t encountered.

C

#include <stdio.h>

int main()

{

    char sen[100];

    scanf("%[^f]s", sen);

    printf("Output : %s", sen);

    return 0;

}

Read scentence

It’ll stop reading after the first occurrence of that character f (specified in the scanset).

Method 2- Using fgets

Note- gets() never checks the maximum limit of input characters. Hence they may cause undefined behavior and probably lead to buffer overflow error which eventually causes the program to crash. Hence, it is advisable not to use the gets function to read strings. To overcome the above limitation, fgets can be used.

Syntax-

char *fgets(char *str, int size, FILE *stream)

C

#include <stdio.h>

#define BUFFSIZE 25

int main()

{

    char sen[BUFFSIZE];

    fgets(sen, BUFFSIZE, stdin);

    printf("Output : %s", sen);

    return 0;

}

Read scentence

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

In this article, we have explained how to take string input in C Programming Language using C code examples. We have explained different cases like taking one word, multiple words, entire line and multiple lines using different functions.

Table of contents:

  1. String input using scanf Function
    1.1. Reading One Word
    1.2. Reading Multiple Words
    1.3. Reading Multiple Words to Form a Line
    1.4. Reading an entire line
  2. Using getchar
  3. Reading Entire Line using gets()
  4. Read One Line at a Time from a File using fgets()
  5. Reading Multiple Lines

Let us learn these techniques using C code examples.

String input using scanf Function

The input function scanf can be used with %s format specification to read in a string of characters.

Reading One Word

For Example :

char instr[10];
scanf("%s",instr);

The problem with the scanf function is that it terminates its input on the first white space it finds. A white space includes blanks,tabs,carraige returns,form feeds and new lines.

Therefore, if the following line of text is typed :

HELLO BOY

then only the string «HELLO» will be read into the array address , since the blank space after the word ‘NEW’ will terminate the reading of string.
The unused locations are filled with garbage.

The scanf function automatically terminates the string that is read with a null character and therefore, the character array should be large enough to hold the input string plus the null character. Note that unlike previous scanf calls, in the case of character arrays, the ampersand (&) is not required before the variable name.

Reading Multiple Words

If we want to read the entire line «HELLO BOY», then we may use two character arrays of appropriate sizes.

char instr1[10], instr2[10];
scanf("%s %s", instr1,instr2);

It will assign the string «HELLO» to instr1 and «BOY» to instr2.

#include<stdio.h>
#include<string.h>
int main()
{
    char instr[100];
  
    printf("Enter a stringn");
    scanf("%s",bin);
    printf("String is : n");
    puts(bin);
    
    return 0;
}

If we give «WELCOME TO OPENGENUS» as input it will only read WELCOME and displays it as output.

To overcome this problem we can make different arrays for all the words present in the string .

Reading Multiple Words to Form a Line

#include<stdio.h>
#include<string.h>
int main()
{
    char instr1[100],instr2[100],instr3[100],instr4[100];
    
    printf("Enter the string of four wordsn");
    scanf("%s",instr1);
    scanf("%s",instr2);
    scanf("%s",instr3);
    scanf("%s",instr4);
    printf("String is : n");
    
    printf("%s %s %s %s" ,instr1,instr2,instr3,instr4 );
    
    return 0;
}

It will take four words in four different character arrays and displays on the output screen.

Reading an entire line

We have seen that scanf with %s or %ws can read only strings without whitespaces.
However, C supports a format specification known as the edit set conversion code %[..] that can be used to read a line containing a variety of characters, including whitespaces.

char instr[100];
scanf("%[^n]",instr);

A similar method to above:

char instr[100];
scanf("%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]", instr);

Using getchar

We can use it repeatedly to read successive single characters from the input and place them into a character array. Thus, an entire line of text can be read and stored in an array. The reading is terminated when the new line character (‘n’)
is entered and the null character is then inserted at the end of the string.

#include<stdio.h>
#include<string.h>
main()
{
    char instr[100] , ch;
    int c = 0;
    printf("Enter the line n");
    do
    {
         ch = getchar();
         instr[c]=ch;
         c++;
    }while(ch != 'n');

    c=c-1;
    instr[c]='';
    printf("%s n", instr);
}

Reading Entire Line using gets()

Another method of reading a string of text containing whitespaces is to use the library function gets available in the <stdio.h> header file.
It reads characters from the keyboard until a new line character is encountered and then appends a null character to the string.
Unlike scanf, it does not skip whitespaces.

For example :

char instr[100];
gets (line);
printf("%s", instr);

It will reads a line from the keyboard and displays it on the screen.

The last program can be also written as :

char instr[100];
printf("%s" , gets(line));

Please note that C does not check for array bounds , so be careful not to input more character that can be stored in the string variable used.

A complete program to demonstrate working of gets :

#include<stdio.h>
#include<string.h>
int main()
{
    char instr[100];
    
    printf("Enter a stringn");
    scanf("%[^n]",instr);
    printf("The output is:-n");
    puts(bin);
    
    return 0;
}

This program will work perfectly fine and it will take the entire string as input from the keyboard and displays it on the output screen.

Read One Line at a Time from a File using fgets()

The function fgets() takes three parameters that is :

  1. string_name
  2. string_max_size
  3. stdin

We can write it as :

fgets(string_name,string_max_size,stdin);

For Example :

#include<stdio.h>
#include<string.h>
int main()
{
    char instr[100];
    
    printf("Enter the stringn");
    fgets(instr,100,stdin);
    printf("The string is:-n");
    puts(bin);
    
    return 0;
}

It will take the entire string as input from the keyboard and displays the entire screen on the output screen.

Reading Multiple Lines

The following program reads multiple line from the keyboard.

#include<stdio.h>
int main()
{
    int s[100];
    printf("Enter multiple line stringsn");
    scanf("%[^r]s",s);
    printf("Entered String isn");
    printf("%sn",s);
    return 0;
}

Question

Which of the following is the correct input statement for reading an entire string from keyboard ?

All of them are correct.

gets(str);

scanf(«%[^n]»,str);

fgets(instr,100,stdin);

All these methods are discussed in the article that is gets() , scanf(«%[^n]»,str); and fgets()

Question

A character array instr[] stores the «HELLO». What will be the length of array instr[] requires to store the string completely ?

6

5

4

None of these

As the word hello is 5 characters long and there will be a null character at end , we require an array of size 6.

Question

State True or False : «The input function gets has one string parameter .»

True

False

The input function gets has one string parameter which reads characters from the keyboard until a new line character is encountered and then appends a null character to the string.

So, with this article at OpenGenus, we have seen all the possible methods to take input string in C programming language.

Summary: in this tutorial, you will learn how to read from a text file using standard library functions such as fgetc() and fgets().

Steps for reading from a text file

To read from a text file, you follow these steps:

  • First, open the text file using the fopen() function.
  • Second, use the fgets() or fgetc() function to read text from the file.
  • Third, close the file using the fclose() function.

Reading from a text file one character at a time

To read from a text file one character at a time, you use the fgetc() function.

The following program reads from the readme.txt file one character at a time and display the file contents to the output:

#include <stdio.h> int main() { char *filename = "readme.txt"; FILE *fp = fopen(filename, "r"); if (fp == NULL) { printf("Error: could not open file %s", filename); return 1; } // read one character at a time and // display it to the output char ch; while ((ch = fgetc(fp)) != EOF) putchar(ch); // close the file fclose(fp); return 0; }

Code language: C++ (cpp)

Reading from a text file line by line

To read a line from a text file, you use the fgets() function:

char * fgets ( char *str, int num, FILE *stream );

Code language: C++ (cpp)

The fgets() function reads characters from the stream and store them into the str.

The fgets() function stops reading if:

  • num-1 characters have been read
  • the newline character or end-of-file character reached.

Note that the fgets() function also includes the newline character in the str.

The following example shows how to use the fgets() function to read a text file line by line and display the text to the output:

#include <stdio.h> int main() { char *filename = "readme.txt"; FILE *fp = fopen(filename, "r"); if (fp == NULL) { printf("Error: could not open file %s", filename); return 1; } // reading line by line, max 256 bytes const unsigned MAX_LENGTH = 256; char buffer[MAX_LENGTH]; while (fgets(buffer, MAX_LENGTH, fp)) printf("%s", buffer); // close the file fclose(fp); return 0; }

Code language: C++ (cpp)

Summary

  • Use the fgetc() function to read from a text file, a character at a time.
  • Use the fgets() function to read from a text file, line by line.

Was this tutorial helpful ?

  • Remove From My Forums
  • Question

  • how i read from txt file, word by word witout to read all line?

Answers

  • Okay then. 

    The short answer is that you can’t read word for word in C#.  So you have two options:

    1. Read line by line and split.
    2. Read character by character and find the splitting characters.

    You have examples of the former.  For the latter, you may want to do something like this. (You’ll probably have to modify this to your liking).

    string filename = @»C:filename.txt»;

    using (StreamReader r = new StreamReader(filename))
    {
        string s = string.Empty;
        int i = 0;
        while ((i = r.Read()) != -1)
        {
            Char c = Convert.ToChar(i);
            if (Char.IsDigit(c) || Char.IsLetter(c))
            {
                s = s + c;
            }
            else
            {
                if (s.Trim() != string.Empty)
                    Console.WriteLine(s);
                s = string.Empty;
            }
        }
    }

    The long and the short of this is, though, that reading the file line by line is the simplest method to accomplish this, and reading it character by character is an extremely complex solution.


    David Morton — http://blog.davemorton.net/

    • Marked as answer by

      Friday, May 8, 2009 3:37 PM

Понравилась статья? Поделить с друзьями:
  • C program files microsoft office office11 excel exe regserver
  • Calculated fields in excel pivot table
  • Calculated columns in excel
  • Calculated column in excel
  • C print word documents