Debug Assertion Failed

Hi guys, I'm replacing 4 letter lower case words with "----" and "|---" for 4 letter words that start with capital letters, my program works except whenever it starts up the dialogue pops up with Debug Assertion Failed, I think has something to do with my cin>>w;, but if I move it outside the while loop it can't stop. Any suggestions to fix it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
#include <ctype.h> 

using namespace std;

int main()
{
	string w;
	cout<<"Enter a sentence"<<endl;
	

	while (w[w.length()-1]!='.')
	{
			cin>>w;

			if(w.length()==4)
		{
			if (w[0]=='a'||w[0]=='b'||w[0]=='c'||w[0]=='d'||w[0]=='e'||w[0]=='f'||w[0]=='g'||w[0]=='h'||w[0]=='i'||w[0]=='j'||w[0]=='k'||w[0]=='l'||w[0]=='m'||w[0]=='n'||w[0]=='p'||w[0]=='o'||w[0]=='q'||w[0]=='r'||w[0]=='s'||w[0]=='t'||w[0]=='u'||w[0]=='v'||w[0]=='w'||w[0]=='y'||w[0]=='x'||w[0]=='z')
			{
				cout<<"---- ";
			}
			else
			{
				cout<<"|--- ";
			}
		}
		else
		{
			cout<<w<<" ";
		}
	}
	cout<<endl;

	return 0;
}
while (w[w.length()-1]!='.')
This seems to be the problem, you are accessing out of bounds, although ur code worked on mine.

Btw you can simplfy the if condition by using islower() function : e.g if( islower( w[0] ) ){ ... }

And the while loop to :
1
2
3
4
5
6
7
8
9
while( cin >> str && str[ str.length() -1 ] != '.' ) { // u can also use .size()
        if( str.length() == 4 ) { 
            if( islower( str[0] ) )
                str = "----";
            else if( isupper( str[0] ) )
                str = "|---";
        }
        cout << str << " ";
    }


EDIT

The last word won't be printed in the code above if it's last character is a ..
You can do this instead : (i think this is ugly)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    while( cin >> str ) {
        if( str[ str.size() - 1 ] != '.' ) {
            if( str.size() == 4 ) {
                if( islower( str[0] ) )
                    str = "----";
                else if( isupper( str[0] ) )
                    str = "|---";
            }
            cout << str << " ";
        } else {
            cout << str;
            break;
        }
    }
Last edited on
it might be something related to the beginning of your loop. Suppose you start the program, at line 9 w is an empty string, w.length() is 0, so w[-1] is what your compiler will probably complain about.
Thanks fixing the while loop to include my cin>>w under the conditions fixed it!
Topic archived. No new replies allowed.