void slova(string datoteka){
    ifstream coban;
    coban.open(datoteka.c_str());
    string polje[200];
    string linija;
    int brojac=0;
    while(!coban.eof()){
    getline(coban,linija);
    polje[brojac]=linija;
    brojac++;
}   

string rec=polje[1];
int brojac2=0;
for(int i=0;i<rec.length();i++){brojac2++;}
cout<<brojac2<<endl;
        
   if(rec[0]==rec[brojac2]){cout<<"same letters"<<endl;}
   else{cout<<"letters are not same"<<endl;}
}

This is my code, it should test if 1st and last letter in string are same, but i can't get it to work.

Please somebody help me, i would really appreciate it.

Thank you in advance.

Dani AI

Generated

Quick diagnosis for : the symptom is an off-by-one read. The loop in the original post increments brojac2 until it equals the string length, then uses that value as an index. The last valid character index is length-1, so indexing at length reads past the end. was right to suggest comparing the first and last character — just make sure you use the correct last index and handle empty strings.

A compact, safe check (C++11+) is to test emptiness and use front()/back():

if (!rec.empty()) {
    if (rec.front() == rec.back())
        std::cout << "same letters\n";
    else
        std::cout << "letters are not same\n";
} else {
    std::cout << "empty string\n";
}

When reading lines from a file, prefer the standard getline loop and a dynamic container instead of while(!eof()) and a fixed-size array. Example improvements: use while (std::getline(file, line)) and std::vector<std::string> so you avoid invalid indexing when fewer lines exist. Also trim a trailing '\r' if files come from Windows (e.g., if (!rec.empty() && rec.back()=='\r') rec.pop_back();) because invisible CR characters can make the last character differ.

Extra tips: always check rec.empty() before indexing; treat single-character strings as valid; prefer rec.size() (returns size_t) for length queries; and validate the number of lines read before accessing polje[1] (or use lines.at(1) to get bounds-checked access). These small checks prevent the off-by-one and out-of-range errors seen in the original code.

Recommended Answers

All 2 Replies

Member Avatar for Member #46692

maybe rec[0] == rec[rec.length()-1]

maybe rec[0] == rec[rec.length()-1]

Thank you man, you are my hero, its working perfrect. :))

Have a nice day!

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.