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
- 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
Благодарю! Так я и думал…
Что ж, я немного переписал код и добился стабильной работы, однако немного не в том виде, в котором нужно:
crane.cpp
Кликните здесь для просмотра всего текста
C++ | ||
|
crane.h
Кликните здесь для просмотра всего текста
C++ | ||
|
main.cpp
Кликните здесь для просмотра всего текста
C++ | ||
|
Данные берутся из этого файла data.txt:
Кликните здесь для просмотра всего текста
Volvo^500^3000
Merlo^1000^5000
MAN^2000^7000
LTECH^5000^10000
Bronto^10000^13000
Pioneer^25000^17000
Wader^50000^20000
По непонятным мне причинам выводится по-другому — обрезаются значения после 2х знаков:
В чём может быть загвоздка? В блоке парсера в crane.php какие только шаманства с
i
и
k
не пробовал…
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 }
- Forum
- Beginners
- Subscript requires array or pointer type
Subscript requires array or pointer type
Hello everyone,
I could really use your help. I am confused about this error that I’m getting. I reread the chapter on pointers and arrays, but I’m still lost. error c2109 subscript requires array or pointer type. Here’s my code:
|
|
You do use subscript operators on lines 3 and 12. Which one has the error? (That information is part of the error message. Do not ignore it.)
At the bottom of http://www.cplusplus.com/doc/tutorial/operators/
is an operator precedence table. The subscript has higher precedence than the dereference operator.
On line 12 you do write:
|
|
Obviously, you cannot use subscript with a char
.
You can reproduce the C2109 with:
|
|
PS. What is the difference between =
and ==
? (Line 12)
Last edited on
The c2109 error is on line 12. I also just noticed the typo on line 12, and fixed it. I guess I’m a little confused on char arrays, I’ll read up in my book and reply back later with more questions.
Topic archived. No new replies allowed.
11-09-2002
#1
Registered User
Error C2109: subscript requires array or pointer type
I am very new to C programming so this may be a silly question. I am recieving the following error and don’t know why:
error C2109: subscript requires array or pointer type
The code that it is pointing to are these three lines:
tempFahr = fahr[indexOfMinFahr];
fahr[indexOfMinFahr] = fahr[fillFahr];
fahr[fillFahr] = tempFahr;Any suggestions? Thanks
11-09-2002
#2
Code Goddess
Is fahr an array? Can we see the declaration?
-Prelude
My best code is written with the delete key.
Recommended Answers
There are some missing ‘{‘ brackets after line 69,75,80. Can you try after fixing them. and if that’s just a typo then plz paste the corrected version.
Jump to Post
swap(exams.at (i).total.at(j)[min],exams.at (i).total.at(j));
What’s the [min] doing?
Jump to Post
you set min to be the value of j, so that statement is equivalent to
exams.at (i).total[j][j]
, but .total is not a two dimensional array, is it? That’s what the error C2109 is about, you’re putting an excess array index on this expression.
Jump to Post
I want to sort the number in descending order…but how to declare a exams.at (i).total.at(j)» in if statement?
> you mean
if((exams.at (i).
Jump to Post
All 13 Replies
Agni
370
Practically a Master Poster
Featured Poster
14 Years Ago
There are some missing ‘{‘ brackets after line 69,75,80. Can you try after fixing them. and if that’s just a typo then plz paste the corrected version.
14 Years Ago
I have done a correction what you had told but it seems still error again..
error C2143: syntax error : missing ‘)’ before ‘}’
67) : error C2780: ‘void __cdecl std::swap(_Ty &,_Ty &)’ : expects 2 arguments — 0 provided
see declaration of ‘swap’
syntax error : missing ‘;’ before ‘}’
: fatal error C1004: unexpected end of file found
412.cpp
: error C2109: subscript requires array or pointer type
subscript requires array or pointer type
subscript requires array or pointer type
: error C2664: ‘void __cdecl std::swap(int &,int &)’ : cannot convert parameter 1 from ‘int’ to ‘int &’
A reference that is not to ‘const’ cannot be bound to a non-lvalue
C:Documents and SettingsashidaMy DocumentsMASTER C++main412.cpp(82) : error C2374: ‘j’ : redefinition; multiple initialization
C:Documents and SettingsashidaMy DocumentsMASTER C++main412.cpp(76) : see declaration of ‘j’
Error executing cl.exe.
#include <iostream> // std::cout
#include <fstream>
#include <iomanip>
#include <string> // std::string
#include <vector> // std::vector<>
#include <algorithm> //std::for each()
using namespace std; // import "std" namespace into global namespace
struct exam
{
int examid;
vector <int> total;
};
void SwapMembers (int items[], int index1, int index2)
{
int temp;
temp=items[index1];
items[index1]=items[index2];
items[index2]=temp;
}
int main()
{
ifstream stream1("STA83SOLUTION.txt");
if ( !stream1.is_open())
{
cout << "While opening a file an error is encountered" << endl;
}
else
{
cout << "Fail Di buka....." << endl;
}
vector <exam> exams;
exam aExam;
int tempExamID;
int tempTotal;
stream1 >> tempExamID >> tempTotal;
aExam.examid = tempExamID;
aExam.total.push_back(tempTotal); // add this exam code to current student's vector of exam codes
while (stream1 >> tempExamID >> tempTotal)
{
if(tempExamID != aExam.examid)
{
exams.push_back(aExam); // no more exam codes for this student. Add aStudent to students vector
aExam.total.clear();
aExam.examid = tempExamID;
}
aExam.total.push_back(tempTotal); // add this exam code to current student's vector of exam codes
}
exams.push_back(aExam); // no more exam codes for this student. Add aStudent to students vector
stream1.close(); // We have read the entire file, so time to close it.
{
ofstream myfile;
myfile.open("411.txt");
int temp;
if (myfile.is_open())
{
for (size_t i = 0; i < exams.size(); i++)
{
for (size_t j = 0; j<exams.at(i).total.size(); j++)
cout<<"n"<<i+1<<":"<<" "<< exams.at (i).total.at(j)<<"t"; // output list of exam codes for this student
}
}
cin.get();
return 0;
for (size_t i = 0; i < exams.size(); i++)
{
for (size_t j = 0; j<exams.at(i).total.size(); j++)
{
int min = i;
for (size_t j = 0; j<exams.at(i).total.size(); j++)
{
if(exams.at (i).total.at(j)[min]<exams.at (i).total.at(j)[j])
min = j;
swap(exams.at (i).total.at(j)[min],exams.at (i).total.at(j));
}
for (size_t j = 0; j<exams.at(i).total.size(); j++)
{
cout << exams.at (i).total.at(j)<<" "<< endl;
}
}
}
}
}
vmanes
1,165
Posting Virtuoso
14 Years Ago
swap(exams.at (i).total.at(j)[min],exams.at (i).total.at(j));
What’s the [min] doing?
14 Years Ago
min means to get the minimum
vmanes
1,165
Posting Virtuoso
14 Years Ago
you set min to be the value of j, so that statement is equivalent to exams.at (i).total[j][j]
, but .total is not a two dimensional array, is it? That’s what the error C2109 is about, you’re putting an excess array index on this expression.
14 Years Ago
I want to sort the number in descending order…but how to declare a exams.at (i).total.at(j)» in if statement?
#include <iostream> // std::cout
#include <fstream>
#include <iomanip>
#include <string> // std::string
#include <vector> // std::vector<>
#include <algorithm> //std::for each()
using namespace std; // import "std" namespace into global namespace
struct exam
{
int examid;
vector <int> total;
};
void SwapMembers (int items[], int index1, int index2)
{
int temp;
temp=items[index1];
items[index1]=items[index2];
items[index2]=temp;
}
int main()
{
ifstream stream1("STA83SOLUTION.txt");
if ( !stream1.is_open())
{
cout << "While opening a file an error is encountered" << endl;
}
else
{
cout << "Fail Di buka....." << endl;
}
vector <exam> exams;
exam aExam;
int tempExamID;
int tempTotal;
stream1 >> tempExamID >> tempTotal;
aExam.examid = tempExamID;
aExam.total.push_back(tempTotal); // add this exam code to current student's vector of exam codes
while (stream1 >> tempExamID >> tempTotal)
{
if(tempExamID != aExam.examid)
{
exams.push_back(aExam); // no more exam codes for this student. Add aStudent to students vector
aExam.total.clear();
aExam.examid = tempExamID;
}
aExam.total.push_back(tempTotal); // add this exam code to current student's vector of exam codes
}
exams.push_back(aExam); // no more exam codes for this student. Add aStudent to students vector
stream1.close(); // We have read the entire file, so time to close it.
{
ofstream myfile;
myfile.open("411.txt");
if (myfile.is_open())
{
for (size_t i = 0; i < exams.size(); i++)
{
for (size_t j = 0; j<exams.at(i).total.size(); j++)
cout<<"n"<<i+1<<":"<<" "<< exams.at (i).total.at(j)<<"t"; // output list of exam codes for this student
if( j< j-1)
swap(j,j+1);
cout<<" "<< exams.at (i).total.at(j);
}
}
cin.get();
return 0;
}
}
Agni
370
Practically a Master Poster
Featured Poster
14 Years Ago
I want to sort the number in descending order…but how to declare a exams.at (i).total.at(j)» in if statement?
> you mean
if((exams.at (i).total.at(j)) < somthing)
14 Years Ago
yess…..the outpu is like this…
1: 25
2: 20
3: 46
4: 56
5: 12
6: 22
and i want to sort in descending order
4: 56
3: 46
1: 25
Agni
370
Practically a Master Poster
Featured Poster
14 Years Ago
you can use any of the sorting algorithms. Try bubble sort, it’s one of the easiest and since the number of elements is not too large you dont need to worry about performance.
before that you need to fix some other errors in your code too. within nested for loops that counter you use should have different names. all your nested loops have ‘j’.
14 Years Ago
but how to make an if statement?
j<j+1 or j+1>j?
Agni
370
Practically a Master Poster
Featured Poster
14 Years Ago
if( j < (j+1) )
{
//code
}
14 Years Ago
I have tried to do a bubble sort..but error..what is ‘size’ : function does not take 1 parameters
error C2660: ‘size’ : function does not take 1 parameters
C:Documents and SettingsashidaMy DocumentsMASTER C++main412.cpp(64) : error C2660: ‘size’ : function does not take 1 parameters
C:Documents and SettingsashidaMy DocumentsMASTER C++main412.cpp(66) : error C2660: ‘size’ : function does not take 1 parameters
C:Documents and SettingsashidaMy DocumentsMASTER C++main412.cpp(67) : error C2660: ‘size’ : function does not take 1 parameters
C:Documents and SettingsashidaMy DocumentsMASTER C++main412.cpp(67) : error C2660: ‘size’ : function does not take 1 parameters
C:Documents and SettingsashidaMy DocumentsMASTER C++main412.cpp(68) : error C2660: ‘size’ : function does not take 1 parameters
Error executing cl.exe.
412.exe — 6 error(s), 0 warning(s)
#include <iostream> // std::cout
#include <fstream>
#include <iomanip>
#include <string> // std::string
#include <vector> // std::vector<>
#include <algorithm> //std::for each()
using namespace std; // import "std" namespace into global namespace
struct exam
{
int examid;
vector <int> total;
};
void SwapMembers (int items[], int index1, int index2)
{
int temp;
temp=items[index1];
items[index1]=items[index2];
items[index2]=temp;
}
int main()
{
ifstream stream1("STA83SOLUTION.txt");
if ( !stream1.is_open())
{
cout << "While opening a file an error is encountered" << endl;
}
else
{
cout << "Fail Di buka....." << endl;
}
vector <exam> exams;
exam aExam;
int tempExamID;
int tempTotal;
stream1 >> tempExamID >> tempTotal;
aExam.examid = tempExamID;
aExam.total.push_back(tempTotal); // add this exam code to current student's vector of exam codes
while (stream1 >> tempExamID >> tempTotal)
{
if(tempExamID != aExam.examid)
{
exams.push_back(aExam); // no more exam codes for this student. Add aStudent to students vector
aExam.total.clear();
aExam.examid = tempExamID;
}
aExam.total.push_back(tempTotal); // add this exam code to current student's vector of exam codes
}
exams.push_back(aExam); // no more exam codes for this student. Add aStudent to students vector
stream1.close(); // We have read the entire file, so time to close it.
{
ofstream myfile;
myfile.open("411.txt");
int temp, flag;
if (myfile.is_open())
{
for (size_t i = 0; i < exams.size(); i++)
{
for (size_t j = 0; j<exams.at(i).total.size(); j++)
{
if (exams.at(i).total.size(j+1) > exams.at(i).total.size(j)) // ascending order simply changes to <
{
temp = exams.at(i).total.size(j); // swap elements
exams.at(i).total.size(j) = exams.at(i).total.size(j+1);
exams.at(i).total.size(j+1) = temp;
flag = 1; // indicates that a swap occurred.
}
cout<<"n"<<i+1<<":"<<" "<< exams.at (i).total.at(j)<<"t"; // output list of exam codes for this student
cout<<" "<< exams.at (i).total.at(j)<<"t";
}
}
}
cin.get();
return 0;
}
}
Agni
370
Practically a Master Poster
Featured Poster
14 Years Ago
you dont need to use ‘size’ in the if statement, you can compare the values itself, using the ‘at’ function was enough.
compare the values «exams.at(i).total.at()»
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.
i know im probably missing something really really stupid… but i changed my (side scroller) code to dynamically load in the size of the level, and dynamically create the memory needed
now, i get errors when trying to access the array, here:
Tile = Levels[CurrentLevel].Data[x][y];
gives me this:
level.cpp(35) : error C2109: subscript requires array or pointer type
Levels is a struct, Data is a a char *, x and y are just DWORDs
Data is initialized by using Data = new char[Width * Height], and it woudn»t work when i used new char[Width][Height]
however it works fine when Data is a char[20][13], and in another function im doing the exact same thing with a Buffer UCHAR *
so what am i doing wrong?
someone, please help me
Levels is a struct? You can»t write Levels[CurrentLevel] if Levels is a struct, Levels must be an array (of sructs).
-Jussi
«ochre chestnut chocolate brown
I»m upside down
on a cosmic eiderdown»
— Ayreon
err.. sorry about that.
level is an array of levels
my problem is with the Data[x][y] bit
this seems to work:
Tile = Levels[CurrentLevel].Data[y * Data.Width + x];
is this alright?
quote: Original post by Quantum
i know im probably missing something really really stupid… but i changed my (side scroller) code to dynamically load in the size of the level, and dynamically create the memory needed
now, i get errors when trying to access the array, here:Tile = Levels[CurrentLevel].Data[x][y];
gives me this:
level.cpp(35) : error C2109: subscript requires array or pointer type
Levels is a struct, Data is a a char *, x and y are just DWORDs
Data is initialized by using Data = new char[Width * Height], and it woudn’t work when i used new char[Width][Height]
however it works fine when Data is a char[20][13], and in another function im doing the exact same thing with a Buffer UCHAR *
Now… there are two ways of doing this… either you use Data[y * Data.Width + x]
or you use Data[x][y]
In the former case, you allocate Data = new char[Width * Height], in the latter you have to
char **Data;Data = new char*[width];for(int i=0;i<width;i++) { Data[ i ] = new char[height]; memset(Data[ i ],0,height);//init to 0 }
Well… I haven’t got a compiler here, but I hope the above is correct
EDIT: It might be possible to use new char[Width][Height] if you declare Data like
char **Data;
but I’m not sure…
//Ksero
Edited by — Ksero on October 13, 2000 7:28:58 AM
thanks Ksero, thats what i thought
now, to continue fixing the rest of my billion or so bugs..
i just thought of this..
how am i supposed to be deleting the array?
do i have to loop through both the width and the height do delete it?
currently im just doing
for(int level = 0; level < NumLevels; level++){ delete [] Levels[level].Data;}
is this right?
i think i may have a memory leak, and im not sure how to check..
BTW im using the method of declaring Data is a char ** and then looping through like ksero showed to allocate the memory
would someone care to answer please?
You delete the rows first, then the *one* column. Time for some ASCII art:
Column
[x]->[y][y][y]
[x]->[y][y][y]
[x]->[y][y][y]
This creates a 3×3 array. In actuality, its a pointer to an array of pointers to arrays. Phew!
so, delete each array that the pointers w/in the first array is pointing to, then the first array:
char** Level;//previously allocatedfor(int i=0;i<Height;i++) delete[] Level<i>;delete[] Level;
——————————
BCB DX Library — RAD C++ Game development for BCB
Edited by — c++freak on October 17, 2000 7:31:26 PM
quote:Data is initialized by using Data = new char[Width * Height], and it woudn»t work when i used new char[Width][Height]
however it works fine when Data is a char[20][13],
Only the last number can be a varialbe: all the other ones have to be constants:
char Data[x][y]; // Wrong, only y can be variable, x must be constantchar Data[23][x][y]; // X must be constantchar Data[23][16]; // Correct
thanks a lot c++freak
zipster, i already knew that, but thanks anyway