Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm very new to c++ and i'm struggling with fixing this string subscript out of range error. It complies but i cannot run it of course.


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string sentence, word = "";
    int wordCounter = 1;
    ifstream file("secret.txt");
    getline(file, sentence); 
    for (int i = 0; i < sentence.length(); i++) {
        if (sentence[i - 1] == ' ') {
            wordCounter++;
            if ((wordCounter) % 5 == 0) {
                word += sentence[i] - 32;
            }
        }
    }
    cout << word;
    return 0;
}


secret.txt is as follows if it matters
January is the first month and december is the last. Violet is a purple color as are lilac and plum.


What I have tried:

My best guess is some condition is not being satisfied but i'm not sure which one.
Posted
Updated 19-Nov-22 9:19am

C++
for (int i = 0; i < sentence.length(); i++) {
    if (sentence[i - 1] == ' ') {

The first time around this loop i is equal to zero, so i - 1 is minus 1 which is an invalid subscript, since it is before the first character of the string. Subscripts start at zero and continue until string.length() -1.
 
Share this answer
 
Look at your code:
C++
for (int i = 0; i < sentence.length(); i++) {
    if (sentence[i - 1] == ' ') {
You start the loop with i set to zero. The first thing you do is try to access the i - 1 element of the array which is index -1.
Since C++ arrays are always zero based, there can never be a negative index, and you get an error.

To be honest, 30 seconds with the debugger would have shown you exactly what you were doing wrong, and saved you some time in trying to find out! The debugger is your best friend with any development, so it's well worth spending a little time getting familiar with at least the basics - Google can help you find out how to use it for your specific IDE.

Think about exactly what you are trying to do, and perhaps read this: How to Write Code to Solve a Problem, A Beginner's Guide[^] before you go any further.
 
Share this answer
 

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