Author Topic: Console Application doesn't work correctly  (Read 6232 times)

Offline l4nd3r

  • Single posting newcomer
  • *
  • Posts: 4
Console Application doesn't work correctly
« on: October 19, 2015, 05:19:12 pm »
I'm having trouble with this encrypt-decrypt program, it compiles but it isn't saving(writing) nor reading the words on the .txt file, but the weird thing is this same code is working on Visual Studio, but as my teacher requires the use of Code::Blocks I'm here asking for help to discover why it isn't working on Code::Blocks.

Also, as I'm Brazilian, so some of the words of the code is in Portuguese, I'll try to give a all around idea of what each function does.

Code
#ifndef _ArquivoDados_
#define _ArquivoDados_

#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

class arquivoDados
{
private:
    // attributes
fstream arquivo;
vector<string> vetor;
char caractere[2];

public:
    // Methods
// Standard builder
arquivoDados(){}

// Storage
void armazenar(char informacao, int num)
{
// Open the file with input mode and concatenation
arquivo.open("ArquivoDeDados.txt", fstream::in | fstream::app);

// Writing the information
if(informacao == '@') // If the information is an "@", turned into a string

arquivo << "&" << endl; // Place an "&" and jumps to another line

else
arquivo << informacao << ";"; // If not, put the information and divides the line with semicolon

// Stores the character
caractere[num] = informacao;

// Close File
arquivo.close();
}

// Storage
void armazenar(string informacao)
{
// Open the file with input mode and concatenation
arquivo.open("ArquivoDeDados.txt", fstream::in | fstream::app);

// Scans each letter of information
for(int i = 0; i < informacao.length(); i++)
if(informacao[i] == caractere[1]) //If it is equal to the second character
informacao[i] = caractere[0]; //  replaces by the first character

arquivo << informacao << ";"; // If not, put the information and divides the line with semicolon

// Close File
arquivo.close();
}

// Reading
void ler(int numLinha)
{
// Clean vector
vetor.clear();

// An auxiliary variable of type String
string temp = "", linha;

// Receive the entire line
// Open the file in output mode
arquivo.open("ArquivoDeDados.txt", fstream::out | fstream::in | fstream::app);

// Read an entire row
for(int j = 0; j < numLinha; j++)
getline(arquivo, linha);

// Close the file
arquivo.close();

// Reading loop
int i;
for(i = 0; i < linha.length(); i++) // Loop to read letter-by-letter
{
if(linha[i] == ';'){ // If the semicolon (end of word)
vetor.push_back(temp); // We store the string in the vector
temp = "";
}
else // If not
temp += linha[i]; // Increment the string with said letter
}
}

// Clear - Clears the TXT file
void clear()
{
// Open in "reading" and "replace modes
arquivo.open("ArquivoDeDados.txt", fstream::out | fstream::trunc);

// Closes the file
arquivo.close();
}

// Returns the number of lines
int quantidadeLinhas() {
// Auxiliary variables
int quantidade = 0; // Number of lines
string aux = "xxxxx"; // Auxiliary String to receive the lines

// Open the file with all modes
arquivo.open("ArquivoDeDados.txt", fstream::in | fstream::out | fstream::app);

// Until we get the empty line (last line)
while(aux != ""){
getline(arquivo, aux); // Reads a line (to check if it is empty)
quantidade++; // Increment the counter
}

// Closes the file to avoid losing data
arquivo.close();

// Returns the value of the entire amount minus 1
return quantidade - 1;
}

void exibir(){
// Loop to scan the vector
int i;
for(i = 0; i < quantidadeLinhas(); i++)
{
// Display the line number that will print
cout << "Pessoa numero " << i + 1 << ":" << endl; //Person Number

// Update vector "vetor" to each 'for' index "i"
ler(i + 1); // You have to put the "i + 1" because the index starts from 0, but the line starts from 1

for(int j = 2; j < vetor.size(); j++)
{
for(int g = 0; g < vetor[j].length(); g++) // Scan every letter of every word
if(vetor[j][g] == vetor[0][0]) // Replacing what is the first character
vetor[j][g] = vetor[1][0]; // For what is the second character

// And printing the word after the change
cout << vetor[j] << endl;
}
}
}
};

#endif
// Main function
int main()
{
// Creates an object of that class
arquivoDados objeto;

// Integer variable to the menu
int opcao = 0;

// Menu
while(opcao != 3)
{
// Opçoes
        cout << "\nMenu:"  << endl;
cout << "1. Gravar Dados"  << endl; // Record data
cout << "2. Exibir Dados"  << endl; // Exhibit data
cout << "3. Sair"  << endl; // Exit or end program
cout << "Digite sua Opcao: "; // Type your option
cin >> opcao; // option

// Switch-Case to treat the cases
switch(opcao)
{
case 1: // If the option to record data
// auxiliary variable
char caractere; // for the first two characters

// User input
cout << "Digite o primeiro caractere: "; //Enter the first character
cin >> caractere;

// Armazena o primeiro caracter e diz que é o primeiro caracter
objeto.armazenar(caractere, 0);

// Entrada do Usuário
cout << "Digite o segundo caractere: "; Type the second character
cin >> caractere;

// Stores the second character and says it is the second character
objeto.armazenar(caractere, 1);

// If the character is different from the "@" (end of line)
while(caractere != '@')
{
// We create a variable to receive the User Input
string informacao;

// Entrada do Usuário
cout << "Digite a informacao (ou arroba para terminar): "; // Enter the information (or at sign to end):
cin >> informacao;

if(informacao == "@") // If it is a "@"...
{
caractere = '@'; //We put the character as '@' (to stop the while)
objeto.armazenar(caractere, 0); // We store the object as a character to the existing check in method
}
else // If any text
objeto.armazenar(informacao); // We store this information
}
break;
case 2: // Exhibition option
// Activate exhibition method
objeto.exibir();
break;
case 3:
// End menu message
cout << "Ate mais"  << endl;
break;
default:
// If chosen option is invalided
cout << "Opcao inexistente" << endl;
break;
}
}

system("pause");
return 0;
}


If anyone has doubt any about a meaning of a word, just ask. Thanks.

Offline stahta01

  • Lives here!
  • ****
  • Posts: 7790
    • My Best Post
Re: Console Application doesn't work correctly
« Reply #1 on: October 19, 2015, 05:28:41 pm »
Learn how to post a full build log and post your code and the "full" build log on a site that supports newbie coders like http://cboard.cprogramming.com/forum.php

http://wiki.codeblocks.org/index.php/FAQ-Compiling_%28errors%29#Q:_How_do_I_troubleshoot_a_compiler_problem.3F

Please read this site FAQs and rules if you wish to post once more on this site.
http://forums.codeblocks.org/index.php/topic,9996.0.html
http://wiki.codeblocks.org/index.php/FAQ

Edit: Just realized a CB Related problem that might cause the issue.
Post the Full Build Log here and the run commands and your file locations.

Edit2: You likely are failing to open the file; you need to always check the file was opened.
I would suggest learning what Compiler your instructor is using; Note, Code::Blocks is NOT a compiler!

Tim S.


« Last Edit: October 19, 2015, 05:34:14 pm by stahta01 »
C Programmer working to learn more about C++ and Git.
On Windows 10 64 bit and Windows 11 64 bit.
--
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org

Offline l4nd3r

  • Single posting newcomer
  • *
  • Posts: 4
Re: Console Application doesn't work correctly
« Reply #2 on: October 20, 2015, 12:35:21 am »
Thanks for answer.

Here is the full build log:
Quote
-------------- Clean: Debug in ArquivoDados (compiler: GNU GCC Compiler)---------------

Cleaned "ArquivoDados - Debug"

-------------- Build: Debug in ArquivoDados (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions  -g     -c C:\Users\alunob12.ACAD\Documents\Trabalho_Agendamusica\ArquivoDados\ArquivoDados.cpp -o obj\Debug\ArquivoDados.o
C:\Users\alunob12.ACAD\Documents\Trabalho_Agendamusica\ArquivoDados\ArquivoDados.cpp: In member function 'void arquivoDados::armazenar(std::string)':
C:\Users\alunob12.ACAD\Documents\Trabalho_Agendamusica\ArquivoDados\ArquivoDados.cpp:53:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
C:\Users\alunob12.ACAD\Documents\Trabalho_Agendamusica\ArquivoDados\ArquivoDados.cpp: In member function 'void arquivoDados::ler(int)':
C:\Users\alunob12.ACAD\Documents\Trabalho_Agendamusica\ArquivoDados\ArquivoDados.cpp:85:31: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
C:\Users\alunob12.ACAD\Documents\Trabalho_Agendamusica\ArquivoDados\ArquivoDados.cpp: In member function 'void arquivoDados::exibir()':
C:\Users\alunob12.ACAD\Documents\Trabalho_Agendamusica\ArquivoDados\ArquivoDados.cpp:139:34: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
C:\Users\alunob12.ACAD\Documents\Trabalho_Agendamusica\ArquivoDados\ArquivoDados.cpp:141:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
mingw32-g++.exe  -o bin\Debug\ArquivoDados.exe obj\Debug\ArquivoDados.o   
Output size is 1010.72 KB
Process terminated with status 0 (0 minutes, 1 seconds)
0 errors, 4 warnings (0 minutes, 1 seconds)
 

The compiler we use is the 'default' GNU GCC Compiler, but he never mentioned this is the one we should use. He just requires the use of Code::Blocks IDE.

And what does CB mean?

Offline stahta01

  • Lives here!
  • ****
  • Posts: 7790
    • My Best Post
Re: Console Application doesn't work correctly
« Reply #3 on: October 20, 2015, 01:31:45 am »
The compiler we use is the 'default' GNU GCC Compiler, but he never mentioned this is the one we should use. He just requires the use of Code::Blocks IDE.

And what does CB mean?

CB or C::B both means Code::Blocks.

You need to follow these steps if you want me to help you.

1. Do a Clean
2. Do a Build
Post that full build log (Looks like you likely already did this part; but, I am NOT sure that you did).
3. Do a Run.
Post the run command.

If you do NOT know how to do one of the steps, ask!

Tim S.

PS: Your instructor may be a Idiot since he did NOT tell the Compiler to use under Code::Blocks.


« Last Edit: October 20, 2015, 01:41:03 am by stahta01 »
C Programmer working to learn more about C++ and Git.
On Windows 10 64 bit and Windows 11 64 bit.
--
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org

Offline l4nd3r

  • Single posting newcomer
  • *
  • Posts: 4
Re: Console Application doesn't work correctly
« Reply #4 on: October 20, 2015, 05:57:50 am »
Sorry, i wasn't at home when i did that log.

Here's the build log:
Quote
-------------- Clean: Debug in ArquivoDados (compiler: GNU GCC Compiler)---------------

Cleaned "ArquivoDados - Debug"
Done.
Quote
-------------- Build: Debug in ArquivoDados (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g  -c C:\Users\Johann\Documents\ArquivoDados\ArquivoDados.cpp -o obj\Debug\ArquivoDados.o
C:\Users\Johann\Documents\ArquivoDados\ArquivoDados.cpp: In member function 'void arquivoDados::armazenar(std::string)':
C:\Users\Johann\Documents\ArquivoDados\ArquivoDados.cpp:53:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
C:\Users\Johann\Documents\ArquivoDados\ArquivoDados.cpp: In member function 'void arquivoDados::ler(int)':
C:\Users\Johann\Documents\ArquivoDados\ArquivoDados.cpp:85:31: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
C:\Users\Johann\Documents\ArquivoDados\ArquivoDados.cpp: In member function 'void arquivoDados::exibir()':
C:\Users\Johann\Documents\ArquivoDados\ArquivoDados.cpp:139:34: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
C:\Users\Johann\Documents\ArquivoDados\ArquivoDados.cpp:141:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
mingw32-g++.exe  -o bin\Debug\ArquivoDados.exe obj\Debug\ArquivoDados.o   
Output file is bin\Debug\ArquivoDados.exe with size 1010.72 KB
Process terminated with status 0 (0 minute(s), 0 second(s))
0 error(s), 4 warning(s) (0 minute(s), 0 second(s))

armazenar = store; ler = read; exibir = display.

3. It's this what you mean by run command?
Quote
-------------- Run: Debug in ArquivoDados (compiler: GNU GCC Compiler)---------------

Checking for existence: C:\Users\Johann\Documents\ArquivoDados\bin\Debug\ArquivoDados.exe
Executing: "C:\Program Files (x86)\CodeBlocks1/cb_console_runner.exe" "C:\Users\Johann\Documents\ArquivoDados\bin\Debug\ArquivoDados.exe"  (in C:\Users\Johann\Documents\ArquivoDados\.)

Offline BlueHazzard

  • Developer
  • Lives here!
  • *****
  • Posts: 3352
Re: Console Application doesn't work correctly
« Reply #5 on: October 20, 2015, 02:20:06 pm »
please note: i have not read your entire code.
You should ALWAYS check for errors on file operation. At least at the open process:
Code
// Open the file with input mode and concatenation
arquivo.open("ArquivoDeDados.txt", fstream::in | fstream::app);

// Writing the information
if(informacao == '@') // If the information is an "@", turned into a string
[...]
you will never know if you opened the file correctly
here the same:
Code
// Open in "reading" and "replace modes
arquivo.open("ArquivoDeDados.txt", fstream::out | fstream::trunc);

i am also pretty sure that you mess with the std::in and std::out flags. Use std::out if you want to write to a file, and std::in if you want to read...
This are general programming (std specific) problems. For future reading ask on a c++ site, this forum is the wrong place for this kind of questions. You can also find help here: http://en.cppreference.com/w/cpp/io/basic_fstream

The c::b related part af your problem:
If you launch a program trough c::b the default search path for your program is the base project folder. So if your file structure looks like this:
Code
MyProgram/MyProgram.cbp
MyProgram/bin/Debug/MyProgram

and you read a file from MyProgram with relative paths (as you do) then your program will search in MyProgram/ folder for the files
If you start your program from the explorer it will search in its own Folder for the file.
So your problem is probably that the files are in the wrong place, but you will never know, because you don't make any error checking.
You can set the search path for your program in Project->Properties->Build Targets->Execution Working dir (note only if you start it from c::b)

And don't blame c::b for this "weird" behaviour. This is a useful feature that most programmer will use. As far as i know also VS uses this principle.

greetings

Offline stahta01

  • Lives here!
  • ****
  • Posts: 7790
    • My Best Post
Re: Console Application doesn't work correctly
« Reply #6 on: October 20, 2015, 02:52:33 pm »
Thanks BlueHazzard; that was the problem I was trying to think of how to describe.

Tim S.

C Programmer working to learn more about C++ and Git.
On Windows 10 64 bit and Windows 11 64 bit.
--
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org

Offline l4nd3r

  • Single posting newcomer
  • *
  • Posts: 4
Re: Console Application doesn't work correctly
« Reply #7 on: October 21, 2015, 12:42:55 am »
Thanks for the answers, i will ask around at a C++ forum. Sorry for any inconvenience.

Edit:

Just to give a update, I got the program working changing the fstream functions to ifstream or ofstream. This topic can be closed now.
Thanks for the help.  :)
« Last Edit: October 22, 2015, 10:02:12 pm by l4nd3r »