How to put together a string | Bytes (2024)

Home Posts Topics Members FAQ

Alex T

How to put together a string | Bytes (1) 29 New Member

This is a snippet of my code that does not work:

Expand|Select|Wrap|Line Numbers

  1. while(ascii!=32)//whilecharacterisnotspace
  2. {
  3. letter=(char)infile.get();//retreivenextcharacter
  4. ascii=(int)letter;
  5. if(ascii==32)
  6. break;
  7. word=word+letter;
  8. }

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 How to put together a string | Bytes (2) 2597 How to put together a string | Bytes (3)

donbock

2,426 How to put together a string | Bytes (6) 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 How to put together a string | Bytes (7) New Member

Here is the complete code for your convenience:

Expand|Select|Wrap|Line Numbers

  1. #include<algorithm>
  2. #include<fstream>
  3. #include<iomanip>
  4. #include<iostream>
  5. #include<map>
  6. #include<string>
  7. //NEEDSTOBEFIXED:FINDSLETTERSNOTWORDS
  8. usingnamespacestd;
  9. typedefmap<string,unsignedint>map_string_int;
  10. typedefmultimap<unsignedint,string>mmap_int_string;
  11. intmain()//intargc,char*argv[]insertintomainfortest
  12. {
  13. charletter;
  14. intcounter=0,number,value;
  15. shortascii=0;
  16. stringword,filename;
  17. mmap_int_string::const_iteratoriElementFound;
  18. map_string_intstring_to_int;
  19. mmap_int_stringint_to_string;
  20. ifstreaminfile;
  21. cout<<"Enternameoffile:";
  22. getline(cin,filename);
  23. infile.open(filename);//argv[1]insertfortest
  24. cout<<endl;
  25. cout<<"letter|ascii|word"<<endl;
  26. while(infile.good())
  27. {
  28. while(!infile.eof())
  29. {
  30. while(ascii!=-1)//whilecharacterisnotspace
  31. {
  32. letter=(char)infile.get();//retreivenextcharacter
  33. cout<<letter<<"|";
  34. ascii=(int)letter;
  35. cout<<ascii<<"|";
  36. if(ascii==-1)
  37. break;
  38. word=word+letter;
  39. cout<<word<<endl;
  40. }
  41. //trytofindwordinindexmap
  42. map_string_int::const_iteratorindexElementFound=string_to_int.find(word);
  43. if(indexElementFound!=string_to_int.end())
  44. {
  45. //iffound,createanotherpairinmultimap
  46. value=indexElementFound->second;
  47. int_to_string.insert(make_pair(value,word));
  48. }else{
  49. //ifnotfound,createpairinbothindexmapandmultimap
  50. counter++;
  51. string_to_int.insert(make_pair(word,counter));
  52. int_to_string.insert(make_pair(counter,word));
  53. }
  54. word="";//clearwordfornextpartoffile
  55. }
  56. //createalistbysearchingmultimap
  57. for(value=0;value<counter;value++)
  58. {
  59. number=int_to_string.count(value);
  60. iElementFound=int_to_string.find(value);
  61. cout<<iElementFound->second<<":"<<number<<endl;
  62. }
  63. }
  64. infile.close();
  65. charresponse;
  66. cin>>response;
  67. return0;
  68. }

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 How to put together a string | Bytes (9) 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

  1. #include<algorithm>
  2. #include<fstream>
  3. #include<iomanip>
  4. #include<iostream>
  5. #include<map>
  6. #include<string>
  7. //NEEDSTOBEFIXED:FINDSLETTERSNOTWORDS
  8. usingnamespacestd;
  9. typedefmap<string,unsignedint>map_string_int;
  10. typedefmultimap<unsignedint,string>mmap_int_string;
  11. intmain()//intargc,char*argv[]insertintomainfortest
  12. {
  13. charletter;
  14. intcounter=0,number,value;
  15. shortascii=0;
  16. stringword,filename;
  17. mmap_int_string::const_iteratoriElementFound;
  18. map_string_intstring_to_int;
  19. mmap_int_stringint_to_string;
  20. ifstreaminfile;
  21. cout<<"Enternameoffile:";
  22. getline(cin,filename);
  23. cout<<filename;
  24. //exit(0);
  25. infile.open(filename.c_str(),ifstream::in);//argv[1]insertfortest
  26. cout<<endl;
  27. cout<<"letter|ascii|word"<<endl;
  28. intout=0;
  29. while(infile.good()&&out==0)
  30. {
  31. while(!infile.eof()&&out==0)
  32. {
  33. while(1)
  34. {
  35. letter=(char)infile.get();//retreivenextcharacter
  36. cout<<letter<<"|";
  37. ascii=(int)letter;
  38. cout<<ascii<<"|";
  39. if(ascii==32||ascii==10)
  40. {
  41. break;
  42. }
  43. if(infile.eof())
  44. {
  45. out=1;
  46. break;
  47. }
  48. word=word+letter;
  49. cout<<word<<endl;
  50. }
  51. //trytofindwordinindexmap
  52. map_string_int::const_iteratorindexElementFound=string_to_int.find(word);
  53. if(indexElementFound!=string_to_int.end())
  54. {
  55. //iffound,createanotherpairinmultimap
  56. value=indexElementFound->second;
  57. int_to_string.insert(make_pair(value,word));
  58. }else{
  59. //ifnotfound,createpairinbothindexmapandmultimap
  60. counter++;
  61. string_to_int.insert(make_pair(word,counter));
  62. int_to_string.insert(make_pair(counter,word));
  63. }
  64. word="";//clearwordfornextpartoffile
  65. }
  66. //createalistbysearchingmultimap
  67. for(value=0;value<counter;value++)
  68. {
  69. number=int_to_string.count(value);
  70. iElementFound=int_to_string.find(value);
  71. if(iElementFound!=int_to_string.end())
  72. {
  73. cout<<endl<<int_to_string.find(value)->second<<":"<<number<<endl;
  74. }
  75. }
  76. }
  77. infile.close();
  78. charresponse;
  79. cin>>response;
  80. return0;
  81. }

Oct 9 '10 #5

reply

donbock

2,426 How to put together a string | Bytes (10) Recognized Expert Top Contributor

Please change line 48 from

Expand|Select|Wrap|Line Numbers

  1. if(ascii==32||ascii==10)

to

Expand|Select|Wrap|Line Numbers

  1. if((ascii=='')||(ascii=='\n'))

Even better would be

Expand|Select|Wrap|Line Numbers

  1. 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 How to put together a string | Bytes (11) New Member

Can you clarify what exactly changed in my code?

Oct 9 '10 #7

reply

Alex T

29 How to put together a string | Bytes (12) 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

9589

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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...

General

9423

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

10215

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++

10049

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 7410

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

5307

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

1 3964

transfer the data from one system to another through ip address

by: 6302768590 |last post by:

Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

C# / C Sharp

2 3564

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 2815

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

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisem*nts and analytics tracking please visit the page.

How to put together a string | Bytes (2024)

References

Top Articles
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated:

Views: 5841

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.