String subscript out of range c ошибка

Ошибка: string subscript out of range C++ Решение и ответ на вопрос 580725

Vlad-letchik

0 / 0 / 0

Регистрация: 08.04.2012

Сообщений: 38

1

20.05.2012, 20:55. Показов 34567. Ответов 9

Метки нет (Все метки)


При запуске выдает ошибку «string subscript out of range». Подскажите, в чем проблема.

C++
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
37
38
39
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string.h>
 
using namespace std;
 
void main( void )
{
 FILE *fp;
 fp = fopen("C:\text.txt","r");
 char *c  = new char[250];
 string src(c);
 string out;
    int start = 0;
    int count = 0;
    int pos = 0;
    for(;;)
    {
       pos = src.find("'",start);
       start++;
       for(;;)
       {
        if (src[start] == '"')
        {
            start++;
            out += src[start];
        }
        else
        {
            break;
        }
 
       }
       out = "n";
       out = "";
    }
 
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



28 / 28 / 8

Регистрация: 20.05.2012

Сообщений: 43

20.05.2012, 21:30

2

Это можно перевести вроде: «Ряд индексов находится за пределами диапазона (Массива или чего-либо). Собственно, что должна делать ваша программа?



0



Avazart

Эксперт С++

8385 / 6147 / 615

Регистрация: 10.12.2010

Сообщений: 28,683

Записей в блоге: 30

20.05.2012, 21:36

3

C++
1
#include <string>// без .h



0



0 / 0 / 0

Регистрация: 08.04.2012

Сообщений: 38

20.05.2012, 22:31

 [ТС]

4

Написать программу, которая считывает текст из файла и выводит на экран только цитаты, то есть предложения, заключенные в кавычки.



0



Precise

28 / 28 / 8

Регистрация: 20.05.2012

Сообщений: 43

21.05.2012, 00:06

5

C++
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
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
 
void main()
{
    string s, str;
    ifstream fin("Text.txt");
    if(fin.is_open())
    {
        while(!fin.eof())
        {
            fin>>s;
            str.append(s);//Метод сцепляющий строки(для получения цельной строки)
        }
    }
    int begin = str.find_first_of('"');//Поиск первой кавычки
    int end =  str.find_last_of('"');//Поиск последней кавычки
 
        for(int i=begin+1; i<end; i++)
        { 
            cout<<str[i]; 
        }
}

Это поиск и вывод экран для одной цитаты, думаю разберетесь, как сделать для множества цитат.)
p. s. Не забываем нажимать спасибо.



6



0 / 0 / 0

Регистрация: 08.04.2012

Сообщений: 38

21.05.2012, 14:15

 [ТС]

6

А можно прокоментировать каждую строчку, а то в программировании я не очень, оно у нас как дополнительный предмет, а прогу нужно сдать, и объяснить код.



0



Precise

28 / 28 / 8

Регистрация: 20.05.2012

Сообщений: 43

21.05.2012, 22:25

7

C++
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
#include <iostream>
#include <string>//для для использования string и его метода append
#include <vector>//Библеотека методов для контейнера vector
#include <fstream>//для чтение/записи файлов
using namespace std;
 
void main()
{
    string s, str;//Объявляем переменные типа стринг
    ifstream fin("Text.txt");//Входной файл из кот. будем читать данные
    if(fin.is_open())//Если файл открыт
    {
        while(!fin.eof())//Пока не кончился файл
        {
            fin>>s;//Читаем строку из файла
            str.append(s);//Метод сцепляющий строки(для получения цельной строки)
        }
    }
    int begin = str.find_first_of('"');//Поиск первой кавычки
    int end =  str.find_last_of('"');//Поиск последней кавычки
 
        for(int i=begin+1; i<end; i++)//Вывод на экран элементов находящися между первой и последней кавычкой строки
        { 
            cout<<str[i]; //Собственно посимвольный вывод на экран элементов
        }
}



2



Vlad-letchik

0 / 0 / 0

Регистрация: 08.04.2012

Сообщений: 38

21.05.2012, 22:30

 [ТС]

8

1)перменная s для строки, а str для файла?
2)

C++
1
 str.append(s);//Метод сцепляющий строки(для получения цельной строки)

а зачем он?



0



Avazart

Эксперт С++

8385 / 6147 / 615

Регистрация: 10.12.2010

Сообщений: 28,683

Записей в блоге: 30

21.05.2012, 22:33

9

C++
1
str.append(s);//Метод сцепляющий строки(для получения цельной строки)

Добавляет в конец строки- s равносильно

C++
1
str+=s;



0



Vlad-letchik

0 / 0 / 0

Регистрация: 08.04.2012

Сообщений: 38

21.05.2012, 22:49

 [ТС]

10

это к 1) вопросу?

Добавлено через 13 минут
Ничего не выводит: я немного исправил, чтобы выводило предложения начинающиеся с тире

C++
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
#include "stdafx.h"
#include <iostream>
#include <string>//для для использования string и его метода append
#include <vector>//Библеотека методов для контейнера vector
#include <fstream>//для чтение/записи файлов
using namespace std;
 
void main()
{
    string s, str;//Объявляем переменные типа стринг
    ifstream fin("D:\dialog.txt");//Входной файл из кот. будем читать данные
    if(fin.is_open())//Если файл открыт
    {
        while(!fin.eof())//Пока не кончился файл
        {
            fin>>s;//Читаем строку из файла
            str.append(s);//Метод сцепляющий строки(для получения цельной строки)
        }
    }
    int begin = str.find_first_of('-');//Поиск тире
    int end =  str.find_last_of(' ');//Поиск окончание реплики(пробел)
 
        for(int i=begin+1; i<end; i++)//Вывод на экран элементов находящися между первой и последней кавычкой строки
        { 
            cout<<str[i]; //Собственно посимвольный вывод на экран элементов
        }
}

Вот содержимое файла: «
-Do you like IT m

-Yes, I like it
ololo
olol-kkj »



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

21.05.2012, 22:49

10

Member Avatar

13 Years Ago

Hi Everybody,

If someone could help me with this problem, I would really appreciate it. I’m a newbie and trying to finish an assignment. I’ve gotten stuck on one thing and can’t seem to find a way out of it. I’ve already done the searches and spent at least 5-6 hours on this little problem alone. I imagine it’s something easy to solve for you guys:

In the code below, every thing works fine until I try to increment the ‘k’ variable (trying to read through a string character by character). Then I get the following warning:

Expression: string subscript out of range

Does anybody know what I can do to solve this?

int main()
{

string keyword;
int check;
int i=0;
int k=0;


char abcd[ARRAY_SIZE] = "ABCDEFGHIJKLMNOPQRSTUVWXY";


ifstream infile;
ofstream outfile;
infile.open ("C:\Users\achirri\Documents\MP6proj.txt");
outfile.open ("I:\C++\MP6proj.txt");





infile >> keyword;



char passkey[ARRAY_SIZE];


for(i = 0; i < ARRAY_SIZE; i++)
    {
		k++;
	check = check_passkey(passkey, ARRAY_SIZE, keyword[k]);
    if (check == 0)   
       passkey[i] = keyword[k];
	abcd_erase(abcd, keyword[k], ARRAY_SIZE);


    }

Edited

13 Years Ago
by Nick Evan because:

Add code-tags


Recommended Answers

Code tags:

[code]

// code goes here

[/code]

So ARRAY_SIZE is 25? 26? Is it defined somewhere? It’s not listed here, and a lot of other stuff isn’t listed either, so it’s impossible to run and it’s hard to see what’s going on. We also don’t …

Jump to Post

Again, use code tags. See post 2 for how. Code is hard to read otherwise.

You got rid of the k++ line, so now k is always 0. Accident? What is this program supposed to do? If you have a keyword called «Phenomenon», passkey and abcd are supposed to …

Jump to Post

All 6 Replies

Member Avatar


VernonDozier

2,218



Posting Expert



Featured Poster


13 Years Ago

Code tags:

[code]

// code goes here

[/code]

So ARRAY_SIZE is 25? 26? Is it defined somewhere? It’s not listed here, and a lot of other stuff isn’t listed either, so it’s impossible to run and it’s hard to see what’s going on. We also don’t know what the input file’s contents are, so we have no idea what keyword is. But if keyword is «house», the program’s going to crash if k is 5 or greater since «house» has 5 letters (therefore it has valid character indexes of 0 through 4).

Without seeing more, I’m guessing that’s your problem. If the length of keyword is less than ARRAY_SIZE, it’s not going to get through the loop without crashing.

Member Avatar

13 Years Ago

Sorry about that. Here’s the full code. I thought the problem could be
figured out with that snippet.

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cctype>

using namespace std;

const int ARRAY_SIZE=26;
const int MAX_ROW=5;
const int MAX_COL=5;


int check_passkey(char p_key[], int length, char searchitem);
void abcd_erase(char a_to_y[], char searchitem, int length);



int main()
{

string keyword;
int check;
int i=0;
int k=0;

char abcd[ARRAY_SIZE] = "ABCDEFGHIJKLMNOPQRSTUVWXY";


ifstream infile;
ofstream outfile;
infile.open ("C:\Users\achirri\Documents\MP6proj.txt");
outfile.open ("I:\C++\MP6proj.txt");





infile >> keyword;



char passkey[ARRAY_SIZE];


for(i = 0; i < ARRAY_SIZE; i++)
    {
		
	check = check_passkey(passkey, ARRAY_SIZE, keyword[k]);
    if (check == 0)   
		passkey[i] = keyword[k];
	abcd_erase(abcd, keyword[k], ARRAY_SIZE);
	

    }


return 0;

}


int check_passkey(char p_key[], int length, char searchitem)
{
    int loc;
    bool found = false;

    for (loc = 0; loc < length; loc++)
    if (p_key[loc] == searchitem)
        {
           found = true;
           break;
        }

    if (found)
       return 1;
    else   
       return 0;
}


void abcd_erase(char a_to_y[], char searchitem, int length)
{
   

    int loc;
    bool found = false;

    for (loc = 0; loc < length; loc++)
    if (a_to_y[loc] == searchitem)
        {
           found = true;
           break;
        }




    if(found)
      for (loc; loc < length; loc++)          //Should be length - 1 ?
        a_to_y[loc] = a_to_y[loc + 1];     

}

Edited

13 Years Ago
by Nick Evan because:

Added code-tags (again)

Member Avatar

13 Years Ago

Oh and «keyword» is being pulled from an external file and is just a
single word, which could be anything, in this case the word is ‘Phenomenon’.

Member Avatar


VernonDozier

2,218



Posting Expert



Featured Poster


13 Years Ago

Again, use code tags. See post 2 for how. Code is hard to read otherwise.

You got rid of the k++ line, so now k is always 0. Accident? What is this program supposed to do? If you have a keyword called «Phenomenon», passkey and abcd are supposed to be changed to what when you’re all done?

Edited

13 Years Ago
by VernonDozier because:

n/a

Member Avatar

13 Years Ago

Okay, thanks for the tips on the code tags. I will look at that. And I accidentally dropped the k++ while trying to work on this problem. Didn’t mean to post without it. Sorry this is confusing. The problem I am trying to solve is to input a word from a file, to pass the characters of that word one by one to an array, without repeating any letters, so a word like ‘vacuum’ has only one of the ‘u’s put in the array. I have a function defined that parses the array to see if a letter already exists in it and passes that info back to the main function to varify. That works okay. The problem I am having is figuring out how to increment the letters of the word I am putting in the array. I was trying to use the k++ to increment through the string letter by letter, but for some reason this is not allowed. I don’t get an error unless I try to increment in this way. So, I assume I must be going out of range in some way, but don’t have much of a clue of what to do about it. Any kind of work around would be helpful.
Thanks.

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cctype>

using namespace std;

const int ARRAY_SIZE=26;
const int MAX_ROW=5;
const int MAX_COL=5;


int check_passkey(char p_key[], int length, char searchitem);
void abcd_erase(char a_to_y[], char searchitem, int length);



int main()
{

string keyword;
int check;
int i=0;
int k=0;

char abcd[ARRAY_SIZE] = "ABCDEFGHIJKLMNOPQRSTUVWXY";


ifstream infile;
ofstream outfile;
infile.open ("C:\Users\achirri\Documents\MP6proj.txt");
outfile.open ("I:\C++\MP6proj.txt");





infile >> keyword;



char passkey[ARRAY_SIZE];


for(i = 0; i < ARRAY_SIZE; i++)
{

check = check_passkey(passkey, ARRAY_SIZE, keyword[k]);
if (check == 0)
passkey[i] = keyword[k];
abcd_erase(abcd, keyword[k], ARRAY_SIZE);
k++

}


return 0;

}


int check_passkey(char p_key[], int length, char searchitem)
{
int loc;
bool found = false;

for (loc = 0; loc < length; loc++)
if (p_key[loc] == searchitem)
{
found = true;
break;
}

if (found)
return 1;
else
return 0;
}


void abcd_erase(char a_to_y[], char searchitem, int length)
{


int loc;
bool found = false;

for (loc = 0; loc < length; loc++)
if (a_to_y[loc] == searchitem)
{
found = true;
break;
}




if(found)
for (loc; loc < length; loc++) //Should be length - 1 ?
a_to_y[loc] = a_to_y[loc + 1];

}

Member Avatar


VernonDozier

2,218



Posting Expert



Featured Poster


13 Years Ago

One, if you are new to C++, I would suggest not using C-Strings at all for this. C-Strings require you to adjust the null terminator. Regular strings do not. You use both in this program. It’s easy to get confused.. I would convert all C-strings to strings.

Two, some type of output would be informative. You have variables manipulated, but never displayed. A display like «Vacuum stripped of all duplicate letters is Vacum» would help. Say explicitly in comments what the display should be.

Three, keep in mind that C++ is case-sensitive. Your array is ‘A’ through ‘Y’. ‘U’ is not ‘u’, so if you compare the two with the == operator, they are not the same. Consider using the toupper function from the cctype library to force capitalization.

Four, if you want to avoid illegal subscript errors, use the strlen function for C strings or the length function from string. If the index you are checking is greater than the length, you could have problems.

string a = "abcdefghij";
string b = "gghhi";
int i = 0;
int k = 0;

while (i < a.length() && k < b.length())
{
    char aChar = a[i];  // no subscript-out-of-range problem
    char bChar = b[k];  // no subscript-out-of-range problem
    // do stuff
}

cout << "b stripped is " << b;  // "gghhi stripped is ghi"


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Нижний индекс строки С++ вне диапазона

Пожалуйста, помогите с отладкой. Это дает мне ошибку «строка индекса вне диапазона ошибок».

Программа должна отсортировать текст, используя алгоритм сортировки вставками.

Вот код:

#include<iostream>
#include<string>
using namespace std;

void insertionSort(string &text, int size) {
  char temp;
  int i;
  for(int j=1;j<size;j++)
  {
    //text.push_back(temp);
    temp=text[j];
    i=j-1;
   while(i>=0 && text[i]>temp)
 {

 text[i+1]=text[i];
  i--;
 }
    text[i+1]=temp;
  }
}

int main()
{
  string text="this a just text need to be sorted";

  int size = text.length();
  insertionSort(text,size);
  cout<<text<<endl;
  return 0;
}

Ошибка отладки утверждения!

Строка:1441:

Выражение: строковый индекс вне допустимого диапазона

я должен изменить text[i+1]=text[j] в text[i+1]=text[i];

Замените

while(text[i]>temp && i>=0)

с

while(i>=0 && text[i]>temp)

Причина:

Когда я становится отрицательным, т.е. i == -1, то сначала проверьте i>=0 вместо проверки на text[i]>temp (который пытается получить доступ к элементу массива в позиции -1 и выходит за пределы диапазона).

EDIT:

также заменить

text[i+1]=text[j];

с

text[i+1]=text[i];

Почему так ? : В сортировка вставок если у нас есть записи больше, чем text[j] в нижней части (т. е. от 0 до j-1), то нам нужно продвинуть эти записи вперед и остановиться в точке, когда у нас больше нет элементов больше, чем text[j].

ответ дан 15 апр.

Вы должны изменить эту инструкцию:

text[i+1]=text[i];

ответ дан 15 апр.

После появления j == 1 ваш цикл while начинается с i==0, затем вы уменьшаете i в цикле, то при следующем выполнении цикла вы проверяете наличие text[i], что неверно (i == -1 здесь)

Для исправления необходимо проверить правильность i первый:

while(i >=0 && text[i] > temp) {
  // ...
}

Это правильно, потому что && действует правило короткого замыкания: если первый операнд (i>=0 в данном случае) приводит к false, остальное выражение (text[i] > temp) не оценивается

ответ дан 15 апр.

У вас есть информация о проблеме. Простой способ решить эту проблему — поместить несколько операторов печати, чтобы узнать значения индекса, используемые с массивом строк.

Еще один комментарий: пожалуйста, не передавайте длину строки, потому что если вы вызовете text.length(); внутри функции перед ее изменением можно получить длину строки.

ответ дан 15 апр.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

c++
string
algorithm
subscript

or задайте свой вопрос.

Понравилась статья? Поделить с друзьями:
  • String or binary data would be truncated sqlstate 22001 error 8152
  • String indices must be integers как исправить
  • Stop code whea uncorrectable error
  • Stop code acpi bios error
  • Stop chassis error ошибка на туарег зимой