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 2598
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
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 31178 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 2793 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 12695 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 29785 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 4114 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 2935 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 4612 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 1996 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 12829 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 |
9591
What is ONU? by: marktang |last post by: ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of... General |
10057
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 |
1 10002 The easy way to turn off automatic updates for Windows 10/11 by: Hystou |last post by: Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,... Windows Server |
9869
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 |
8883
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 7415
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 |
5449 Windows Forms - .Net 8.0 by: adsilva |last post by: A Windows Forms form does not have the event Unload, like VB6. What one acts like? Visual Basic .NET |
2 3575
How to add payments to a PHP MySQL app. by: muto222 |last post by: How can i add a mobile payment intergratation into php mysql website. PHP |
3 2816
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 |