-3

I am trying to make a program in which a user enters a string and i will print out the second word in the string with its size. The delimiter's are space( ), comma(,) and tab( ). I have used a character array and fgets to read from user and a character pointer that points to the first element of the array.

source code:

#include"iostream"
#include<stdio.h>
#include<string>

using namespace std;

// extract the 2nd word from a string and print it with its size(the number of characters in 2nd word)

int main()
{
    char arr[30], arr1[30];
    char *str = &arr1[0];

    cout<<"Enter a string: ";
    fgets(str, 30, stdin);

    int i = 0, j, count = 1, p = 0;     // count is used to find the second word
    // j points to the next index where the first delimiter is found.
    // p is used to store the second word found in character array 'arr'

    while(*(str+i) != '\n')
    {
        if(*(str+i) == ' ' || *(str+i) == ',' || *(str+i) == '  ')
        {
            count++;

            if(count == 2)
            {
                // stroing 2nd word in arr character array
                j = i+1;    
                while(*(str+j) != ' ' || *(str+j) != ',' || *(str+j) != '   ')
                {
                    arr[p] = *(str+j);
                    cout<<arr[p];
                    p++;
                    i++;
                    j++;
                }
                break;
            }

        }
        i++;
    }

    arr[p+1] = '\0';        // insert NULL at end

    i = 0;
    while(arr[i] != '\0')
    {
        cout<<arr[i];
        i++;
    }

    cout<<"("<<i<<")"<<endl;

    return 0;
}

Help me out with this.

Mat
  • 188,820
  • 38
  • 367
  • 383
  • its much easier if you dont mix two different languages. better decide for one and write the code accordingly – 463035818_is_not_a_number Jan 17 '19 at 16:20
  • 1
    That's *very* easy using the functionality of the C++ standard library. So, do you want a C solution or a C++ solution? Pick *one*. – Some programmer dude Jan 17 '19 at 16:20
  • 1
    Are you developing in C, or C++? C++ has `std::string`, which has [`std::string::find_first_of`](https://en.cppreference.com/w/cpp/string/basic_string/find_first_of), which simplifies the lookup of delimiters, while C - doesn't. – Algirdas Preidžius Jan 17 '19 at 16:22
  • 1
    Your question is missing the input with expected output and what's going wrong. I can answer this question various ways but the question as written is basically asking for someone to create the solution for you. – Matt Jan 17 '19 at 16:31
  • @Someprogrammerdude i need a C++ answer – Lakshya Munjal Jan 17 '19 at 16:41
  • @AlgirdasPreidžius i just want to use the basic string functions like at() to create a solution in C++ – Lakshya Munjal Jan 17 '19 at 16:59
  • @LakshyaMunjal "_i just want to use the basic string functions like at() to create a solution in C++ _" I am sorry, but I don't understand what you mean by that. What is "basic function", by your definition? `std::string`, has member function `find_first_of` (I linked to it), doesn't it accomplish basically the same thing, as most of your code posted? – Algirdas Preidžius Jan 17 '19 at 18:09
  • Possible duplicate of [Parse (split) a string in C++ using string delimiter (standard C++)](https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c) – kanstar Jan 17 '19 at 19:49

4 Answers4

1

The delimiters used when extracting from a stream depends on the locale currently in effect. One (cumbersome) way to change the extraction behaviour is to create a new locale with a special facet in which you specify your own delimiters. In the below example the new locale is used to imbue a std::stringstream instead of std::cin directly. The facet creation part is mostly copy/paste from other answers here on SO, so you'll find plenty of other examples.

#include <iostream>
#include <locale>    // std::locale, std::ctype<char>
// https://en.cppreference.com/w/cpp/locale/ctype_char
#include <sstream>   // std::stringstream
#include <algorithm> // std::copy_n
#include <vector>    // a container to store stuff in

// facet to create our own delimiters
class my_facet : public std::ctype<char> {
    mask my_table[table_size];
public:
    my_facet(size_t refs = 0)
        : std::ctype<char>(&my_table[0], false, refs)
    {
        // copy the "C" locales table to my_table
        std::copy_n(classic_table(), table_size, my_table);
        // and create our delimiter specification
        my_table[' '] = (mask)space;
        my_table['\t'] = (mask)space;
        my_table[','] = (mask)space;
    }
};

int main() {
    std::stringstream ss;
    // create a locale with our special facet
    std::locale loc(std::locale(), new my_facet);
    // imbue the new locale on the stringstream
    ss.imbue(loc);

    while(true) {
        std::string line;
        std::cout << "Enter sentence: ";
        if(std::getline(std::cin, line)) {
            ss.clear(); // clear the string stream from prior errors etc.
            ss.str(line); // assign the line to the string stream

            std::vector<std::string> words; // std::string container to store all words in
            std::string word; // for extracting one word

            while(ss>>word) { // extract one word at a time using the special facet
                std::cout << "  \"" << word << "\" is " << word.size() << " chars\n";
                // put the word in our container
                words.emplace_back(std::move(word));
            }
            if(words.size()>=2) {
                std::cout << "The second word, \"" << words[1] << "\", is " << words[1].size() << " chars\n";
            } else {
                std::cout << "did not get 2 words or more...\n";
            }
        } else break;
    }
}
Ted Lyngmo
  • 37,764
  • 5
  • 23
  • 50
0

To start, don't use std::cin for testing. Just set a value in your code for consistency and ease of development. Use this page for a reference.

#include <iostream>
#include <string>

int main() {
    std::string str("this and_that are the tests");
    auto start = str.find_first_of(" ,\n", 0);
    auto end = str.find_first_of(" ,\n", start + 1);
    std::cout << str.substr(start, end - start);
    return 0;
}

And this is still somewhat of a hack, it just depends where you are going. For instance the Boost library is rich with extended string manipulation. If you are going to parse out more than just one word it can still be done with string manipulations, but ad-hoc parsers can get out of hand. There are other tools like Boost Spirit to keep code under control.

lakeweb
  • 1,727
  • 2
  • 13
  • 17
0
#include"iostream"
#include<stdio.h>
#include<string>
#include <ctype.h>

using namespace std;


int main()
{
    char c;
    string str;
    char emp = ' ';
    cout<<"Enter a string: ";
    getline (cin,str);


    int  j = 0, count = 1, counter = 0;  


    for (int i = 0; i < str.length() && count != 2; i++)
    {
        cout<< str[i] <<endl;
        if( isspace(str[i]) || str[i] == ',' || str[i] == '\t' )
        {
            count++;

            if(count == 2)
            {
                j = i+1;
                while(j < str.length())
                {
                    if (isspace(str[j]) || str[j] == ',' || str[j] == '\t')
                    {
                        break;

                    }
                    cout<<str[j];
                    counter++;
                    j++;
                }
                cout<<endl;
            }

        }
    }



    cout<<"size of the word: "<<counter<<endl;

    return 0;


}

This is a simple answer to what you want, hope to help you.

0
// Paul Adrian P. Delos Santos - BS Electronics Engineering
// Exercise on Strings

#include <iostream>
#include <sstream>

using namespace std;

int main(){
    
    // Opening Message
    
    cout << "This program will display the second word and its length.\n\n";
    
    // Ask for a string to the user.
        
    string input;   
    cout << "Now, please enter a phrase or sentence: ";
    getline(cin, input);
    
    // Count the number of words to be used in making a string array.
    
    int count = 0;
    int i;
    
    for (i=0; input[i] != '\0'; i++){
        if (input[i] == ' ')
            count++;        
    }
    
    int finalCount = count + 1;
    
    // Store each word in a string array.
    
    string arr[finalCount];
   
    int j = 0;
    stringstream ssin(input);
   
    while (ssin.good() && j < finalCount){
        ssin >> arr[j];
        j++;
    }
    
    // Display the second word and its length. 
    
    string secondWord = arr[1];
    
    cout << "\nResult: " << arr[1] << " (" << secondWord.size() << ")";
    
    return 0;
}
fcdt
  • 2,151
  • 5
  • 9
  • 24