Alex T
29 New Member
This is a snippet of my code that does not work:
Expand|Select|Wrap|Line Numbers
- while(ascii!=32)//whilecharacterisnotspace
- {
- letter=(char)infile.get();//retreivenextcharacter
- ascii=(int)letter;
- if(ascii==32)
- break;
- word=word+letter;
- }
I use a text file with 3 words "this this this". The string word records the letters that are found but when it gets to the spacebar, with ascii code 32, instead prints -1 and the "y with dots over it symbol" goes into the string.
How should I fix this?
Oct 7 '10 #1
Subscribe Reply
7 2620
ash*tpro 542 Recognized Expert Contributor
Try printing letter after line 3 and ascii after line 4
Send the results.
Oct 8 '10 #2
reply
donbock 2,426 Recognized Expert Top Contributor
What is word? Is it a string where the plus sign is overloaded to mean concatenate or is it an integral type? If it is an integral type then computing the sum of several characters is not going to be meaningful.
What is the initial value of ascii? That is, why do you expect to be able to get into the while loop?
By the way, replace the magic number "32" with character constant ' '.
Oct 8 '10 #3
reply
Alex T 29 New Member
Here is the complete code for your convenience:
Expand|Select|Wrap|Line Numbers
- #include<algorithm>
- #include<fstream>
- #include<iomanip>
- #include<iostream>
- #include<map>
- #include<string>
- //NEEDSTOBEFIXED:FINDSLETTERSNOTWORDS
- usingnamespacestd;
- typedefmap<string,unsignedint>map_string_int;
- typedefmultimap<unsignedint,string>mmap_int_string;
- intmain()//intargc,char*argv[]insertintomainfortest
- {
- charletter;
- intcounter=0,number,value;
- shortascii=0;
- stringword,filename;
- mmap_int_string::const_iteratoriElementFound;
- map_string_intstring_to_int;
- mmap_int_stringint_to_string;
- ifstreaminfile;
- cout<<"Enternameoffile:";
- getline(cin,filename);
- infile.open(filename);//argv[1]insertfortest
- cout<<endl;
- cout<<"letter|ascii|word"<<endl;
- while(infile.good())
- {
- while(!infile.eof())
- {
- while(ascii!=-1)//whilecharacterisnotspace
- {
- letter=(char)infile.get();//retreivenextcharacter
- cout<<letter<<"|";
- ascii=(int)letter;
- cout<<ascii<<"|";
- if(ascii==-1)
- break;
- word=word+letter;
- cout<<word<<endl;
- }
- //trytofindwordinindexmap
- map_string_int::const_iteratorindexElementFound=string_to_int.find(word);
- if(indexElementFound!=string_to_int.end())
- {
- //iffound,createanotherpairinmultimap
- value=indexElementFound->second;
- int_to_string.insert(make_pair(value,word));
- }else{
- //ifnotfound,createpairinbothindexmapandmultimap
- counter++;
- string_to_int.insert(make_pair(word,counter));
- int_to_string.insert(make_pair(counter,word));
- }
- word="";//clearwordfornextpartoffile
- }
- //createalistbysearchingmultimap
- for(value=0;value<counter;value++)
- {
- number=int_to_string.count(value);
- iElementFound=int_to_string.find(value);
- cout<<iElementFound->second<<":"<<number<<endl;
- }
- }
- infile.close();
- charresponse;
- cin>>response;
- return0;
- }
My goal for this is to find the frequency of each word in the text file.
The text file has only the word "this".
For convenience, I have altered the code to make the output more meaningful: here it is.
Enter name of file: C:\\test1.txt
letter | ascii | word
t | 116 | t
h | 104 | th
i | 105 | thi
s | 115 | this
| -1 |
This is as far as it gets before the program stops functioning. Please assist.
Oct 8 '10 #4
reply
ash*tpro 542 Recognized Expert Contributor
ascii value -1 represents end of file and not space.
space has ascii value 32.
There are lots of logical problems in this code.
I have fixed the few of them. see if this code runs at your end. This is g++ compliant, you may need to make few changes.
Expand|Select|Wrap|Line Numbers
- #include<algorithm>
- #include<fstream>
- #include<iomanip>
- #include<iostream>
- #include<map>
- #include<string>
- //NEEDSTOBEFIXED:FINDSLETTERSNOTWORDS
- usingnamespacestd;
- typedefmap<string,unsignedint>map_string_int;
- typedefmultimap<unsignedint,string>mmap_int_string;
- intmain()//intargc,char*argv[]insertintomainfortest
- {
- charletter;
- intcounter=0,number,value;
- shortascii=0;
- stringword,filename;
- mmap_int_string::const_iteratoriElementFound;
- map_string_intstring_to_int;
- mmap_int_stringint_to_string;
- ifstreaminfile;
- cout<<"Enternameoffile:";
- getline(cin,filename);
- cout<<filename;
- //exit(0);
- infile.open(filename.c_str(),ifstream::in);//argv[1]insertfortest
- cout<<endl;
- cout<<"letter|ascii|word"<<endl;
- intout=0;
- while(infile.good()&&out==0)
- {
- while(!infile.eof()&&out==0)
- {
- while(1)
- {
- letter=(char)infile.get();//retreivenextcharacter
- cout<<letter<<"|";
- ascii=(int)letter;
- cout<<ascii<<"|";
- if(ascii==32||ascii==10)
- {
- break;
- }
- if(infile.eof())
- {
- out=1;
- break;
- }
- word=word+letter;
- cout<<word<<endl;
- }
- //trytofindwordinindexmap
- map_string_int::const_iteratorindexElementFound=string_to_int.find(word);
- if(indexElementFound!=string_to_int.end())
- {
- //iffound,createanotherpairinmultimap
- value=indexElementFound->second;
- int_to_string.insert(make_pair(value,word));
- }else{
- //ifnotfound,createpairinbothindexmapandmultimap
- counter++;
- string_to_int.insert(make_pair(word,counter));
- int_to_string.insert(make_pair(counter,word));
- }
- word="";//clearwordfornextpartoffile
- }
- //createalistbysearchingmultimap
- for(value=0;value<counter;value++)
- {
- number=int_to_string.count(value);
- iElementFound=int_to_string.find(value);
- if(iElementFound!=int_to_string.end())
- {
- cout<<endl<<int_to_string.find(value)->second<<":"<<number<<endl;
- }
- }
- }
- infile.close();
- charresponse;
- cin>>response;
- return0;
- }
Oct 9 '10 #5
reply
donbock 2,426 Recognized Expert Top Contributor
Please change line 48 from
Expand|Select|Wrap|Line Numbers
- if(ascii==32||ascii==10)
to
Expand|Select|Wrap|Line Numbers
- if((ascii=='')||(ascii=='\n'))
Even better would be
Expand|Select|Wrap|Line Numbers
- if(isspace(ascii))
Lines 45 and 47 print the character before you check to see if it is a space. Thus, a single trailing space gets printed with each word. Is that what you wanted to do?
Don't you want to discard leading spaces too? Consider a state machine with two states: in-a-word and between-words. The initial state is between-words. Any non-whitespace character causes a transition from between-words to in-a-word. Any whitespace character causes a transition from in-a-word to between-words.
Oct 9 '10 #6
reply
Alex T 29 New Member
Can you clarify what exactly changed in my code?
Oct 9 '10 #7
reply
Alex T 29 New Member
Nevermind, don't. I fixed the problem. Thank you all for your help.
Oct 9 '10 #8
reply
Sign in to post your reply or Sign up for a free account.
Similar topics
5 31185 Want to split string on 1 or more white spaces by: Stu Cazzo |last post by: I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it will split myString up using the delimiter of 1 space so that Java |
8 2797 String vs new String by: Grant Wagner |last post by: I'm a bit confused by String() (typeof 'string') vs new String() (typeof 'object'). When you need to access a method or property of a -String-, what type is JavaScript expecting (or rather, what should you provide), a -String object- or a -string-? Given the following benchmark: var t = (new Date()).getTime(); for (var ii = 0; ii < 100000; ++ii) { var x = (String('hi')).charAt(0); // typeof 'string' Javascript |
7 12696 String enumeration/grouping by: archway |last post by: I know you cannot have string enumerations such as: enum myStringEnum { enumItem1 = "value 1", enumItem2 = "value 2", etc } However, I was wondering whether you had ever created something that would mimic this? I have tried the following: C# / C Sharp |
1 953 StringBuilder AppendFormart cannot handle String!! by: Jay Balapa |last post by: Hello, If I use AppendFormat with string as a parameter. I get string cannot be converted to IFormatProvider. This occurs in 2.0 Thanks. Jay ASP.NET |
1 29786 PHP Fatal error: Cannot use string offset as an array by: Jim Michaels |last post by: => Array ( => UML:CLASS => open => 5 => Array ( => .:00000000000008EC => quiz_batteries => public PHP |
6 4118 Help with "cannot assign string" error by: Don Lancaster |last post by: I need to progrmatically do this inside a loop this.fh03.value = fixFloat (Harms, numPoints) ; with the numbers changing per an index. If I try curHvals = "03" ; // (derived from index to provide leading zero) Javascript |
7 2940 Cannot post string "union select" php form by: php_mysql_beginer911 |last post by: Hi .. hope someone will help i am trying to figure it out why i cannot post string "union select" every time i try to post data which content union and select .. the page doesn't get posted and it shows error page not found on this server i googled and found some people use union and select to hack sites (mysql injection) i guess the server i am using has some kind of filter and if a post string content "union select" ... it simply... PHP |
5 4613 Cannot use string offset as an array by: samatair |last post by: I get an error message like this. Fatal error: Cannot use string offset as an array in D:\www\site\includes\change_preference.inc.php on line 310 $cityName = $row2; The above code is causing this error. Please let me know what is wrong with this code. How can I rectify this error. Here $i, $j consists of integer value. which are used to perform a for loop specific number of times. while $row2 brings data from a database. PHP |
1 1999 Cannot get string input to work by: andrewc |last post by: I am trying to get a 2 character string into my program in order to then determine a command based on the string. This is in an embedded application. Right at the top of my program I have declared static char comin; // declared as 'static' - I will use it in a number of places . . . void main () C / C++ |
19 12835 Cannot Convert string to class type by: Queen Soso |last post by: hi there, When I run this line I get an error: obj.number_type = dropdownlist1.selectedItem.value; number_type is a class type and I want to put a string value in it from a drop down list. this is the error: C# / C Sharp |
9629 Changing the language in Windows 10 by: Hystou |last post by: Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,... Windows Server |
10727
Problem With Comparison Operator <=> in G++ by: Oralloy |last post by: Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in... C / C++ |
10442
Maximizing Business Potential: The Nexus of Website Design and Digital Marketing by: jinu1996 |last post by: In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is... Online Marketing |
10171
Discussion: How does Zigbee compare with other wireless protocols in smart home applications? by: tracyyun |last post by: Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some... General |
9269
AI Job Threat for Devs by: agi2029 |last post by: Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea... Career Advice |
1 7712
Access Europe - Using VBA to create a class based on a table - Wed 1 May by: isladogs |last post by: The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will... Microsoft Access / VBA |
6920 Couldnt get equations in html when convert word .docx file to html file in C#. by: conductexam |last post by: I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();... C# / C Sharp |
5595 Trying to create a lan-to-lan vpn between two differents networks by: TSSRALBI |last post by: Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls... Networking - Hardware / Configuration |
3 3057
Comprehensive Guide to Website Development in Toronto: Expert Insights from BSMN Consultancy by: bsmnconsultancy |last post by: In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive... General |