help what to do with std::map , std::isalnum

I got some tips to use std::map , std:isalnum. But I dont know how to use them can anyone help me and explain me better how and when to use them ?

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 #include <fstream>
#include<bits/stdc++.h> 
#include <iostream>
#include <string>
#include <sstream>
#include <map>

using namespace std;



 main ()
 {
 	
     ifstream tekstas;   
     ofstream rezultatas; 
     tekstas.open ("tekstas.txt"); 
     char sim, raides [60]; 
     int n, kuri, kiekis [60], i ,j; 
     bool tinka, yra; 
     n = -1; 
     for ( int i = 0; i < 60; i++)   	
     {
         raides[i] = ' '; 
         kiekis[i] = 0; 
     } 
     while ( tekstas.get (sim) )
     {
        kuri = 0; 
        tinka = ((sim != ' ') && (sim != '.') && (sim != ',') && (sim != '(') && (sim != ')'));
        tinka = ( tinka && (sim != '-') && (sim != ';') && (sim != '+'));        
        if ( tinka ) 
        {
            yra = false; 
            for ( int i = 0; i <= n; i++) if ( raides [i] == sim )
            {
                kuri = i; 
                yra = true; 
            }
            if ( yra ) kiekis[kuri]++; 
            else
            {
                n++; 
                raides[n] = sim;
                kiekis[n]++; 
            }
        }
     }

     rezultatas.open ("rez.txt"); 
     for (int i = 0; i <= n; i++) rezultatas << raides[i] << "   " << kiekis[i] << endl; 
 		
     rezultatas.close ();
     tekstas.close (); 
     return 0; 
}



The Program int char bool is in Lithuanian I can translate if needed
Hello Qikee,

While I look over the program Would you please provide the file for input. Or at least a fair sample if it is large.

Having the same file that you are using will elevate any guess work about what the program is using.

First look at your program a few blank lines would make it easier to read.

Andy
text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Hello Qikee,

Thank you for the file.

I have yet to run the program, but what I see first is:

The header files:
1
2
3
4
5
6
7
8
9
10
11
12
//#include<bits/stdc++.h>  // <--- Duplicates what you have used below and adds more header files that you may not need.
#include <fstream>
#include <iostream>
#include <iomanip>  // <--- Added. Used for "std::quoted()".
#include <string>
//#include <sstream>
//#include <map>
#include <cctype>  // <--- Added.
#include <chrono>  // <--- Added.
#include <thread>  // <--- Added.

using namespace std;  // <--- Best not to use. 

I have found that "iostream" should be followed by "iomanip" as I quite often use it in most programs. These are manipulators for "cin", "cout" anf file streams that can be very handy.

The header files "sstream", which I do not see used, and "map" can be commented out for now. At the moment I am not sure why "map" was suggested or where it would be useful.

In my setup I believe that "cctype" may have been included through "iostream", but do not count on this as your compiler and header files may be different. And it does not cause any problem if you try to include a header file a second time.

"chrono" and "thread" I will talk about shortly.

The last line the comment says all I am going to say for now. There have been many posts here the cover this if you want to do a search and http://www.lonecpluspluscoder.com/2012/09/22/i-dont-want-to-see-another-using-namespace-xxx-in-a-header-file-ever-again/ is always a good read.

Line 12 of your code should be int main(). "main" always returns an "int", usually zero (0), to say how the program ended.

On line 17 you open a file stream, but how do you know it is open? If the file did not open the program would continue, but would not read anything.

When dealing with a file stream I like to use this:
1
2
3
4
5
6
7
8
9
10
const std::string inFileName{ "text.txt" };

std::ifstream inFile(inFileName);

if (!inFile)
{
	std::cout << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread". Optional as is the header files.
	return 1;  //exit(1);  // If not in "main".
}

I put the file name in a variable to make it easier to use.

Line 3 not only defines the name of the file stream, but also tries to open the file.

The if statement is checking that the file stream is open and ready to use.

Line 8 is optional. The way my IDE is setup when a "return" or "exit" is executed the window that the program was running in closes and I do not have enough time to read any last messages.

The line optional and if you choose not to use it you will not need the header files "chrono" and "thread".

For now the only part you have to worry about is the number in (). This is the whole number of seconds that the program will pause or wait for.

For your variables:
1
2
3
char sim{}, letters[60]{};
int n{ -1 }, which{}, content[60]{}, i{}, j{};
bool fit{}, is{};

From C++11 standards on the use of empty {}s makes it easy to initialize your variables. I feel that it is a good idea to initialize the variables when they are defined. If for no other reason I like to know that the variables contain something other than garbage. And sometimes using an uninitialized variable can cause an error at compile time.

Sorry for the variable names. I tried to translate most of the program all at once and it did not work as well as I had hoped for.

Using the {}s will initialize the "char"s to "\0" and the array to all "\0"s. The "int"s will be zero(0) and the array will be all zeros. The bool variables will be zero of "false" or you could put "true" between the {}s.

Defining n{ -1 } and content[60]{}, what you have as "kiekis" would eliminate the need for lines 21 - 26

Lines 30 and 31:
Line 30 will set a value for "tinka" and line 31 could change that value and that may be a problem. I will know more when I run the program.

After that I will need to see the program while its running to understand more.

At the end of the program you open a file for output. You could check it like I did for the input file, but it is not as necessary because if the file does not exist it will create it before it writes to the file.

I started to mention this earlier before I I got into something else. Take a look at http://www.cplusplus.com/reference/cctype/ It can give you some ideas of what and how you can use the functions.

I am curious about where this program came from. Was it from a class or a book and if a book what is the title.

Hope that helps,

Andy
Thank You very much!
The program was made by me and the help of my teacher. I asked the internet about it and some gave me a tip to use map and isalnum because I wanted to make the output file in alphabetic order (forgot to mention that).
And a question why do you not recommend using namespace std;? And how can I input from file using script because With some help from my friend I wrote a new one but neither of us know how to make so it inputs the text from the file. I think he got it from somewhere. (suspicious)
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
#include <map>
#include <iostream>
#include <string>
#include <cctype>
#include <fstream>

int main()
{
	char ch;
	std :: ifstream tekstas;
	std :: ofstream rezultatas;
	tekstas.open("tekstas.txt") ;
	rezultatas.open ("rez.txt");
    std::map<char, int> themap;
    std::string test = ch;
    while (tekstas.get(ch))
    for (size_t i = 0; i < test.size(); ++i)
    {
         ch = test[i];
        if (isalnum(ch))
          themap[ch]++;
    }
    
    for (auto& m : themap)   
		   
        rezultatas << "Raide '" << m.first << "' buvo panaudota  " << m.second << " tiek kartu\n";
        rezultatas.close ();
        tekstas.close() ;
        return 0;
}        

Last edited on
using namespace std can conflict with other names. You'll be coding like a champ, your code wont work, you wont know why, you'll realize your code is using the wrong version of some function because the "std" namespace has a function with the same name.

EDIT: Much better to use:

1
2
3
using std::cout;
using std::endl;
using std::cin;
Last edited on
Hello Qikee,

A much better program.

Watch your indenting. I do realize that when putting something in a message between "code" tags the indenting tends to be exaggerated. Mixing spaces and tabs together may also be a problem.

I see that you changed line 9. I guess you figured out the the constant character pointer did not work. making it a constant means that you can not change the value of the variable. And the pointer part is unnecessary, but may have worked.

Line 15 is not needed as you are reading one character at a time from the input file.

Lines 17, 18, 19 and line 22 are not needed. Creating a std::string with one character is making more work than you need. The while loop and the if statement is all you need. The if statement will create a map in alphabetical order based on the letters in the file. Although I would suggest using "std::isalpha(ch)" unless you want numbers to be in the map.

This is what I did with your code:
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
40
41
42
43
44
45
46
47
48
#include <cctype>
#include <iostream>
#include <iomanip>
#include <string>

#include <map>
#include <fstream>
#include <chrono>
#include <thread>

int main()
{
	char ch;
	std::map<char, int> themap;
	//std::string test; // <--- Not needed.

	std::string inFileName{ "text.txt" };

	std::ifstream tekstas(inFileName);

	if (!tekstas)
	{
		std::cout << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread".
		return 1;  //exit(1);  // If not in "main".
	}

	std::ofstream rezultatas;
	rezultatas.open("rez.txt");

	//for (char lc = 'A'; lc <= 'Z'; lc++)
	//{
	//	themap[lc] = 0;
	//	themap[lc + 32] = 0;
	//}

	while (tekstas.get(ch))
			if (isalpha(ch))
				themap[ch]++;

	for (auto& m : themap)
		rezultatas << "Raide '" << m.first << "' buvo panaudota  " << m.second << " tiek kartu\n";

	rezultatas.close();
	tekstas.close();

	return 0;
}

The order of the header files usualy makes no difference, but I have found that when the first section is in alphabetical order it helps to see if you have missed something. And the first section is generally what you would use in any progrsm. The second section are any header files that are needed by the program you are working on.

You really need to check that the input file is open and ready to use or the rest of the program will execute, but nothing will happen.

The output file is OK for now, but you should check that it did not have any problem. especially if you use a path to the file.

The for loop that is commented out will create a map of all upper and lower case letters. This will contain the entire alphabet and allow you to see any letters that were not used.Not using the for loop will create a map of only the letters that are found in the file and how many times each letter appears.

Whether you use the for loop or not is up to you. It is just a suggestion for an alternative.

Note: Notice how I used blank lines to break up the code and make it easier to read. The compiler does not care about white space in the code, but someone who is trying to read it does.

Hope that helps,

Andy
Thank you very much Andy , you are a very great person
Topic archived. No new replies allowed.