Айгулька 0 / 0 / 0 Регистрация: 11.01.2011 Сообщений: 7 |
||||
1 |
||||
11.01.2011, 18:17. Показов 14431. Ответов 7 Метки нет (Все метки)
битый час пытаюсь исправить и не получается всё равно( Добавлено через 26 минут
__________________
0 |
5053 / 3114 / 271 Регистрация: 11.11.2009 Сообщений: 7,045 |
|
11.01.2011, 18:33 |
2 |
1 |
55 / 55 / 9 Регистрация: 18.03.2010 Сообщений: 345 Записей в блоге: 1 |
|
11.01.2011, 18:33 |
3 |
int i,a=0; //здесь ‘а’ — имя переменной // а сдесь а — это уже имя массива, хоть ‘а’ объявлена выше как переменная, а не как массив
2 |
5053 / 3114 / 271 Регистрация: 11.11.2009 Сообщений: 7,045 |
|
11.01.2011, 18:36 |
4 |
А, не, фиг, а надо объявить как массив Добавлено через 1 минуту
0 |
romedal 55 / 55 / 9 Регистрация: 18.03.2010 Сообщений: 345 Записей в блоге: 1 |
||||
11.01.2011, 18:47 |
5 |
|||
1 |
0 / 0 / 0 Регистрация: 11.01.2011 Сообщений: 7 |
|
11.01.2011, 19:27 [ТС] |
6 |
сделала всё как написали и теперь другая ошибка: error C2664: massiv: невозможно преобразовать параметр 1 из ‘int’ в ‘int []’ Добавлено через 1 минуту Добавлено через 2 минуты
0 |
sandye51 программист С++ 841 / 600 / 147 Регистрация: 19.12.2010 Сообщений: 2,014 |
||||
11.01.2011, 19:47 |
7 |
|||
1 |
0 / 0 / 0 Регистрация: 11.01.2011 Сообщений: 7 |
|
11.01.2011, 21:10 [ТС] |
8 |
спасииибо)
0 |
I am trying to debug some homework but I am having trouble with these lines of code
#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
int main()
{
char word;
cout << "Enter a word and I will tell you whether it is" << endl <<
"in the first or last half of the alphabet." << endl <<
"Please begin the word with a lowercase letter. --> ";
cin >> word;
if(word[0] >= 'm')
cout << word << " is in the first half of the alphabet" << endl;
else
cout << word << " is in the last half of the alphabet" << endl;
return 0;
}
I get the following error and I have no clue what its sayings
error C2109: subscript requires array or pointer type
Deanie
2,3042 gold badges18 silver badges35 bronze badges
asked May 13, 2010 at 20:13
numerical25numerical25
10.4k35 gold badges128 silver badges208 bronze badges
The term subscript refers to the application of []
operator. In your word[0]
, the [0]
part is a subscript.
The built-in []
operator can only be used with arrays or pointers. You are trying to use it with an object of type char
(your word
is declared as char
), which is neither an array nor a pointer. This is what the compiler is telling you.
answered May 13, 2010 at 20:15
2
Another suggestion: declare output text as one entity, then block write. This may make your programs easier to debug, read and understand.
int main(void)
{
static const char prompt[] =
"Enter a word and I will tell you whether it isn"
"in the first or last half of the alphabet.n"
"Please begin the word with a lowercase letter. --> ";
string word;
cout.write(prompt, sizeof(prompt) - sizeof(''));
getline(cin, word);
cout << word;
cout << "is in the ";
if(word[0] >= 'm')
cout "first";
else
cout << "last";
cout << " half of the alphabetn";
return 0;
}
For Your Information (FYI):
stdafx.h
is not a standard header
and not required for small projects.conio.h
is not a standard header
and not required for simple console
I/O.- Prefer
string
for text rather than
char *
.
answered May 13, 2010 at 21:54
Thomas MatthewsThomas Matthews
56.2k17 gold badges98 silver badges151 bronze badges
Instead of
char word;
declare
string word;
You already included the string-class header. Then you can access the elements with the []-operator.
Additional remark: Why do you use conio.h? It is obsolete and is not part of the C++ standard.
answered May 13, 2010 at 20:36
2
word is declared as a char
, not an array. But you’re using word[0]
.
answered May 13, 2010 at 20:14
dcpdcp
54k22 gold badges141 silver badges164 bronze badges
Permalink
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
-
Go to file
-
Copy path
-
Copy permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2109 |
Compiler Error C2109 |
11/04/2016 |
C2109 |
C2109 |
2d1ac79d-a985-4904-a38b-b270578d664d |
Compiler Error C2109
subscript requires array or pointer type
The subscript was used on a variable that was not an array.
The following sample generates C2109:
// C2109.cpp int main() { int a, b[10] = {0}; a[0] = 1; // C2109 b[0] = 1; // OK }
Permalink
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
-
Go to file
-
Copy path
-
Copy permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2109 |
Compiler Error C2109 |
11/04/2016 |
C2109 |
C2109 |
2d1ac79d-a985-4904-a38b-b270578d664d |
Compiler Error C2109
subscript requires array or pointer type
The subscript was used on a variable that was not an array.
The following sample generates C2109:
// C2109.cpp int main() { int a, b[10] = {0}; a[0] = 1; // C2109 b[0] = 1; // OK }
Я столкнулся с небольшой проблемой, связанной с циклом for и массивом, и я надеюсь, что смогу получить некоторую помощь. В первой функции использование цикла for для вызова каждого значения функции работает просто отлично. Тем не менее, во второй функции я получаю сообщение об ошибке из Visual Studio о том, что «индекс требует массив или тип указателя». Что я делаю не так здесь, что вызывает эту ошибку?
Целью этой программы является поиск в текстовом файле книг, пропуск строк между записями, выяснение, сколько записей в файле соответствует и где они находятся, и распечатка деталей каждой записи.
void bookSearch(string id) {
ifstream fbooks;
string item = " ", entry = " ";
int resultLocation[30];
int searchType = 0;
fbooks.open("books.txt");
cout << "Welcome to the Book Search System, " << id << ".n"<< "What do you wish to search the registry by?n"<< "1. ISBN Numbern" << "2. Authorn" << "3. Titlen";
while (searchType<1 || searchType>3) {
cin >> searchType;
if (searchType<1 || searchType>3) {
displayMessage(0);
}
}
getline(cin, item);
for (int x = 0; x <= 30; x++) {
for (int y = 0; y < searchType; y++)
getline(fbooks, entry);
if (entry == item)
resultLocation[x] = 1;
else
resultLocation[x] = 0;
for (int z = 0; z < 5; z++)
getline(fbooks, entry);
}
resultPrint(resultLocation, id);
}void resultPrint(int resultLocation, string id){
int resultNum = 0;
string entry = "";
ifstream fbooks;
fbooks.open("books.txt");
for (int a = 0; a <= 30; a++) {
if (resultLocation == 1)
resultNum++;
}
if (resultNum > 0) {
cout << endl << "There are " << resultNum << " entries in the database matching that criteria.n";
for (int a = 0; a <= 30; a++){
if (resultLocation[a] == 1) { //The a in this line is marked with the error
for (int b = 0; b <= 2; b++) {
getline(fbooks, entry);
cout << entry;
}
}
}
}
else
cout << endl << "There are no entries in the database matching that criteria.n";
}
0
Решение
resultLocation
является целым числом, поэтому вы не можете использовать operator[]
на нем (кроме первого «указателя»). Похоже, вы хотели создать массив:
void resultPrint(int resultLocation[], string id);
0
Другие решения
- Forum
- Beginners
- error C2109: subscript requires array or
error C2109: subscript requires array or pointer type
Hi everyone, I’m new to C++ programming. I got a task to sort students mark in ascending order using bubble sorting. The marks are given in the text file. I had try to solve it but error still occurred and i don’t know how to solve the errors. Hoping anyone can help me. Thanks for your kindness.
Here is the text file. (first column indicate matricNum, second column marks and third are gender)
001 65.5 2
002 56.7 2
003 35.8 1
004 42 2
005 49.4 1
006 55.1 1
007 87.5 2
|
|
The output should be:
003 35.8 1
004 42 2
005 49.4 1
006 55.1 1
002 56.7 2
001 65.5 2
007 87.5 2
error C2109: subscript requires array or pointer type
Does your compiler/IDE show the line that causes that error? It should.
Lines 24, 36, 38, 39, 40, 47:
|
|
You do use those three variables like they were arrays.
Then again, you never use the array double numb[7];
Hi yat89,
Errors/warnings for your file:
In function 'int main()': 24:33: error: invalid types 'int[int]' for array subscript 24:45: error: invalid types 'double[int]' for array subscript 24:58: error: invalid types 'int[int]' for array subscript 36:15: error: invalid types 'double[int]' for array subscript 36:26: error: invalid types 'double[int]' for array subscript 38:19: error: invalid types 'double[int]' for array subscript 39:12: error: invalid types 'double[int]' for array subscript 39:23: error: invalid types 'double[int]' for array subscript 40:12: error: invalid types 'double[int]' for array subscript 47:31: error: invalid types 'double[int]' for array subscript 10:9: warning: unused variable 'numb' [-Wunused-variable]
I believe your issue is that you never actually use your numb array.
Your error is that you are attempting to use matricNum as an array (by accessing it as matricNum[i]), but matricNum is simple an int.
Perhaps you meant to use numb instead of matricNum?
Similarly, marks
is not an array
.
If you want it to be an array, declare it as such,
perhaps double marks[7];
Last,
for (i=0;i<=7;i++)
Please note that if your array has 7 elements in it, accessing my_array[7] is out of bounds of the array, because arrays start at 0.
I would change the <= to just <.
Last edited on
Topic archived. No new replies allowed.
- Remove From My Forums
-
Question
-
i am trying to create n sequences of vector and each with different number of elements.
So, first i create the number of sequences which is n, then i also create the index for each sequence. Last, i enter the elements for each sequence.
i have been thinking for like half an hour, and still have no clue where went wrong. can someone tell me where?
int main()
{
int n,number;
cin>>n;
vector<int> array;
array.resize(n);for (int x=0; x<n; x++)
{
cin>>number;
for (int y=0; y<number; y++)
{
cin>>array[x][y];
}
}}
Answers
-
array is a vector of int.
array[x] is an element of this vector. Therefore it is an int.
array[x][y] is a meaningless expression because you cannot apply the expression [y] to an int.You talk of a sequence of vectors. In order for that to happen, you need to have more than one vector. You have a couple of options:
You could define a vector of vectors — vector<vector<int>> array;
You could define an array of vectors — vector<int> array[10];While technically still only one vector, you could also define a vector of arrays — vector<int[100]> array; which would allow you to use the syntax array[x][y].
On the other hand, if you tell us what you want to do rather than how you intend to do it, we may be able to offer better suggestions.
-
Proposed as answer by
Monday, September 26, 2016 7:04 AM
-
Marked as answer by
Hart Wang
Monday, October 10, 2016 6:22 AM
-
Proposed as answer by
#include <stdio.h>
#include <iostream>
using namespace std;
int main(void)
{
bool premiereLignefaite = false;
//Lire le fichier
FILE * graphe = fopen("graphe.txt", "r");
//Fichier de sortie
FILE * resultat = fopen("resultat.txt", "w");
int nbr1, nbr2;
int *matrice; //pointeur vers la matrice d'adjacence
//Ligne lue
static char ligne[50];
while (fgets(ligne, 50, graphe) != NULL) //retourne 0 quand on a end-of-file
{
//La premiere ligne est différente
if (premiereLignefaite == false) {
//Initialiser une matrice d'adjacence NxN
sscanf(ligne, "%d %d", &nbr1, &nbr2);
matrice = new int(nbr1 * nbr1); //Memoire dynamique pour la matrice dadjacence n x n
premiereLignefaite = true;
continue;
}
//On construit notre matrice d'adjacence
sscanf(ligne, "%d %d", &nbr1, &nbr2);
matrice[nbr1][nbr2] = 1;
}
int u = 2+2;
return 0;
}
Итак, я получаю сообщение об ошибке в этой строке:
matrice [nbr1] [nbr2] = 1;
Я просто пытаюсь создать список смежности из текстового файла. Я не понимаю, что я делаю неправильно. Спасибо.
EDIT: поскольку люди спрашивают об этом, это мой графический файл. Первая строка — количество вершин и число ребер (не полезно imo)
Следующие строки являются моими ребрами, я использую первую строку для выделения памяти для графика NxN и следующих строк для заполнения моей матрицы смежности.
9 20
0 1
0 2
1 0
1 2
1 3
1 5
2 0
2 1
2 3
3 1
3 2
3 4
4 3
5 1
5 6
5 7
6 5
6 8
7 5
8 6