Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
This is the question : IARCS Problem Archive[^]

What I have tried:

I've written the code as follows, although up to my knowledge, it is logically and syntactically correct, it gives a runtime error. Any suggestions and tips are welcome.
C++
#include<bits stdc++.h="">
using namespace std;
#define c temp[j]

int main()
{
    ios::sync_with_stdio(false);
    vector<string> words;
    string temp,uni;
    int N,i,j,start,no=0;

    //Input and Computation
    cin >> N;
    for(i = 0;i < N;i++)
    {
        getline(cin,temp);//Getting the line of text
        start = 0;
        for(j = 0;j < (int)temp.length();j++)//Extracting words and storing in vector
        {
            if(c >= 65 && c <= 90)
                c = c + 32;

            if(c == ' '||c == '.'||c == ';'||c == ','||c == ':')
            {
                uni = temp.substr(start,j-start-1);
                words.push_back(uni);
                no++;
                start = j;
            }
        }
        temp = "";
    }
    sort(words.begin(),words.end());

    //Output
    cout << no;
    for(i = 0;i < no-1;i++)//Removing duplicates
    {
        if(words[i] != words[i+1])
            cout << words[i] <<'\n';
    }
    cout << words[no-1];

    return 0;
}
Posted
Updated 1-Nov-16 9:40am
v2
Comments
KarstenK 1-Nov-16 13:57pm    
you must provide the full error and on which line.
[no name] 1-Nov-16 14:04pm    
"Any suggestions and tips are welcome", learn how to use the debugger to debug your code, learn how to ask questions in technical forums and don't expect people from half way around the world to read your mind.

C++
uni = temp.substr(start,j-start-1);


looks like a potential out-of-bounds.

if j==0, this will be
C++
temp.substr(0, -1);
 
Share this answer
 
Comments
jeron1 1-Nov-16 15:35pm    
I noticed that as well, apparently 'string::npos' is a valid 2nd parameter for substr(), and it's value happens to be -1. I doubt however that the code was written with that in mind.
compiling and running the code, and giving it "this is a line" as input, the code asserts on
C++
cout << words[no-1];


because words is empty.

so, apparently it is not "logically and syntactically correct".
 
Share this answer
 
Comments
jeron1 1-Nov-16 15:49pm    
..and no is unnecessary, as it's always equal to words.size().

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900