GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 19-Nov-2009, 15:17
jnCPP jnCPP is offline
New Member
 
Join Date: Oct 2009
Posts: 15
jnCPP will become famous soon enough

Need guidance with strchr


I'm currently working on a program that requires me to read strings from a file "teams.txt"
Code:
DELAWARE ST.:BLUE HENS:187:162:171 DELAWARE ST.:HEDGE HOGS:199:123:175 DELAWARE ST.:CANAL SKIERS:151:126:165 DELAWARE ST.:NEWARK NUTS:183:188:191 ARKANSAS ST.:WINKERS:136:121:149 ARKANSAS ST.:FLIPPERS:177:181:187 ARKANSAS ST.:ARK RIDERS:173:173:173 ARKANSAS ST.:SUNEVS:196:189:190

I need to break up the strings using strchr, strcpy, atoi, atof, but my instructor expects us to use the book to figure this out; the problem is that our book doesn't cover these subjects, and my professor is currently away on a family emergency.
I don't know where to start, so a push in the right direction would be greatly appreciated.

A couple of questions:
- Can I use cin.getline() to read from the file, or is there a different method to get the string?
- Regardless of which method I use to get the string from the file, can I store the retrieved information into an array? For example:
CPP / C++ / C Code:
// assuming the inFile code and necessities are previously written)
int j = 0;
char teamInfo[51]
cin.getline( teamInfo[j], 50)
while( inFile )
{
j++;
cin.getline( teamInfo[j], 50)
}
  #2  
Old 19-Nov-2009, 16:29
Howard_L Howard_L is offline
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 932
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: Need guidance with strchr


Maybe strtok() will do the job for you:
CPP / C++ / C Code:
#include <iostream>
using namespace std;

int main(void)
{
  char *cp, s[] = "Hello and how are you today \n";

  cout << s;
  cp = strtok(s, " d");
  while( cp != NULL )
  {  
    cp = strtok(NULL, " d");
    cout << cp << " \n";
  }
}
/*
man strtok   or:
[url]http://www.cplusplus.com/reference/clibrary/cstring/strtok/[/url]

char * strtok ( char * str, const char * delimiters );
*/
  #3  
Old 20-Nov-2009, 13:14
TanLorik TanLorik is offline
Junior Member
 
Join Date: Nov 2009
Posts: 38
TanLorik has a spectacular aura aboutTanLorik has a spectacular aura about

Re: Need guidance with strchr


actually, i don't think strtok is food for this...(or maybe i don't know how to use it)

anyway, here's what i think the process operation should be like:
(note, not exactly sure what you wanted to do with the output, so I showed it on screen, and pasted in a txt file, according to what you need to do, you can modify the string further using the same method).

CPP / C++ / C Code:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <fstream>
using namespace std;

int main()
{	char teamInfo[51], city[51], name[51], numbers[51];
	int i=1;
	ifstream inFile("teams.txt");
	ofstream outFile("teams2.txt");
	inFile.getline(teamInfo, 51);
	while(!inFile.eof())
		{strncpy(city, teamInfo, strlen(teamInfo)-strlen(strchr(teamInfo, ' ')));
		city[strlen(teamInfo)-strlen(strchr(teamInfo, ' '))] = NULL;
		strcpy(teamInfo, strchr(teamInfo, ' '));
		strncpy(name, teamInfo, strlen(teamInfo)-strlen(strchr(teamInfo, '1')));
		name[strlen(teamInfo)-strlen(strchr(teamInfo, '1'))]=NULL;
		strcpy(teamInfo, strchr(teamInfo, '1'));
		strcpy(numbers, teamInfo);
		cout << "team #"<< i << " " << name << "with the number: "<< numbers << "comes from the city: " << city << endl;
		outFile << "team #"<< i << " " << name << " with the number: "<< numbers << " comes from the city: " << city << endl;
		inFile.getline(teamInfo, 51);
		}
	inFile.close();
	outFile.close();
	system("pause");
}



my output:
Code:
team #1 ST.:BLUE HENS: with the number: 187:162:171 comes from the city: DELAWARE team #2 ST.:HEDGE HOGS: with the number: 199:123:175 comes from the city: DELAWARE team #3 ST.:CANAL SKIERS: with the number: 151:126:165 comes from the city: DELAWARE team #4 ST.:NEWARK NUTS: with the number: 183:188:191 comes from the city: DELAWARE team #5 ST.:WINKERS: with the number: 136:121:149 comes from the city: ARKANSAS team #6 ST.:FLIPPERS: with the number: 177:181:187 comes from the city: ARKANSAS team #7 ST.:ARK RIDERS: with the number: 173:173:173 comes from the city: ARKANSAS
  #4  
Old 20-Nov-2009, 19:21
jnCPP jnCPP is offline
New Member
 
Join Date: Oct 2009
Posts: 15
jnCPP will become famous soon enough

Re: Need guidance with strchr


Thanks a lot!
Just seeing how strchr/strcpy are used helped 100%,
I'm going to try to figure out how to use strchr to find the ":" and change it to "\0", and from there I"ll use strcpy to get each string set into the right structure. Thanks again.
  #5  
Old 20-Nov-2009, 21:03
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 350
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Need guidance with strchr


Quote:
Originally Posted by jnCPP
Thanks a lot!
Just seeing how strchr/strcpy are used helped 100%,
I'm going to try to figure out how to use strchr to find the ":" and change it to "\0", and from there I"ll use strcpy to get each string set into the right structure. Thanks again.

I'm not sure where the "CPP" part of your "jnCPP" name comes into play, but whatever it is that you're doing is most definitely NOT C++ code. It is a mixture of C and C++ that is, at best, a bastardization of both languages.

You may want to describe the data format in more detail. I don't know what the integer number sequences are related to in your data. They kind of look like the combined scores of three games for "both teams" in a basketball game or something. In other words, how do we separate them from the text file into something more meaningful if we don't know what they mean?

Decide if you're using C or C++. Inter-mixing the two at this level is probably not a good idea. Here is a C-centric example using strtok:

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM_DATA_POINTS_PER_LINE        (5)

void parse_n_print_char_data(char* p_szdata)
{
    int count = 0;
    char *token, *seps = ":\n\r\t";
    token = strtok(p_szdata, seps);

    while(token != NULL)
    {
        if((count % NUM_DATA_POINTS_PER_LINE == 0) && count > 0)
        {
            printf("\n");
            count = 0;
        }
        printf("%s\n", token);
        ++count;
        token = strtok(NULL, seps);
    }
    printf("\n\n");
}

int main()
{
    size_t done;
    FILE* infile;

    char buf[BUFSIZ] = {0};

    printf("Enter data file name: ");
    fgets(buf, BUFSIZ, stdin);
    buf[strlen(buf) -1] = '\0';

    infile = fopen(buf, "r");
    if(infile != NULL)
    {
        do
        {
            done = fread(buf, sizeof(char), BUFSIZ, infile);
            if(done > 0)
            {
                parse_n_print_char_data(buf);
            }
        } while(!done);
        fclose(infile);
    }
    else
    {
        printf("Error opening file %s\n", buf);
    }

    return 0;
}


Output:

Code:
Enter data file name: data.txt DELAWARE ST. BLUE HENS 187 162 171 DELAWARE ST. HEDGE HOGS 199 123 175 DELAWARE ST. CANAL SKIERS 151 126 165 DELAWARE ST. NEWARK NUTS 183 188 191 ARKANSAS ST. WINKERS 136 121 149 ARKANSAS ST. FLIPPERS 177 181 187 ARKANSAS ST. ARK RIDERS 173 173 173 ARKANSAS ST. SUNEVS 196 189 190


Noting, of course, that there is an obvious "bug" in this code whereby if the entire file is not within BUFSIZ bytes, then the parse function is unlikely to work properly. Just a little side angle for those who would submit it without checking.


MxB
  #6  
Old 21-Nov-2009, 04:22
TanLorik TanLorik is offline
Junior Member
 
Join Date: Nov 2009
Posts: 38
TanLorik has a spectacular aura aboutTanLorik has a spectacular aura about

Re: Need guidance with strchr


Quote:
Originally Posted by jnCPP
I'm going to try to figure out how to use strchr to find the ":" and change it to "\0", and from there I"ll use strcpy to get each string set into the right structure. Thanks again.


I don't recommend using /0 as it is a NULL character, and a NULL character signifies the end of the char array. try using ' '(space) instead.

Quote:
Originally Posted by Mexican Bob
I'm not sure where the "CPP" part of your "jnCPP" name comes into play, but whatever it is that you're doing is most definitely NOT C++ code. It is a mixture of C and C++ that is, at best, a bastardization of both languages.

MxB, I think he's in the same bucket as me, out school teacher is extremly outdated with current C++ (heck, my teacher doesn't know what namespace std is >.<"), and we might have pick some hybrid coding habits, if you see such habits, now or in the future, can you please point them out to the CPP version? thanks.
  #7  
Old 21-Nov-2009, 09:22
Howard_L Howard_L is offline
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 932
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: Need guidance with strchr


Quote:
I don't recommend using /0 as it is a NULL character, and a NULL character signifies the end of the char array. try using ' '(space) instead.
Hold on thar whipper-snapper!
C strings are traditionally terminated by one byte with the value of zero affectionately known
as the "null" character and for which the constant '\0' is defined for use in your code.
You'll sometimes see descripters named to indicate this like MBob's "p_szdata" up there.
That's (pointer to string zero-terminated)data. The sz is more of a windows style thing.

NULL is an int sized void pointer with the value of zero.
I get a warning if I try to use NULL as you have above.
CPP / C++ / C Code:
#include <iostream>
using namespace std;

int main()
{
  char *cp= NULL, s[]= "Hello", *sp = "Hello";  // quoted strings are automatically z-termed
  int i, len;

  cout << "cp is NULL: " << (void*)cp << "  sizeof(NULL) is: " << sizeof(NULL) 
       << "  sizeof('\\0') is: " << sizeof('\0') << "\n";

  cp = s;
  cout << "cp is: " << (void*)cp << ",  s is: " << (void*)s << "\n";

  len = sizeof(s);
  cout << "sizeof(s) is: " << len << ",  strlen(s) is: " << strlen(s) << "\n";
  
  cout << "Values of characters in s. (note the zero terminator (zterm)) \n";
  cout.setf( ios::hex , ios::basefield );
  cout.fill('0');
  cout.width(2);

  for(i= 0; i < len; i++)
    cout << (int)s[i] << "  "; 
  cout << "\n";
   
  for(i= 0; i < len; i++)
    cout << (int)*sp++ << "  ";
  cout << "\n";

  i = 0;
  while( s[i] != '\0' )
    cout.put( s[i++] );
   cout << "\n";

  i = 0;
  while( s[i] != NULL )    // warning: NULL used in arithmetic
    cout.put( s[i++] );
   cout << "\n";

  cout << endl;
}
Code:
cp is NULL: 0 sizeof(NULL) is: 4 sizeof('\0') is: 1 cp is: 0xbf99bb95, s is: 0xbf99bb95 sizeof(s) is: 6, strlen(s) is: 5 Values of characters in s. (note the zero terminator (zterm)) 48 65 6c 6c 6f 0 48 65 6c 6c 6f 0 Hello Hello
jnCPP's statement above:
Quote:
I'm going to try to figure out how to use strchr to find the ":" and change it to "\0",
makes sense and is exactly what strtok() does to the target string!
Yes , it messes it up. Do some experiments and see for yourselves.

As far as your instructor learning you old stuff, there's nothing wrong with knowing the basic building blocks.
Last edited by Howard_L : 21-Nov-2009 at 10:41.
  #8  
Old 21-Nov-2009, 10:01
TanLorik TanLorik is offline
Junior Member
 
Join Date: Nov 2009
Posts: 38
TanLorik has a spectacular aura aboutTanLorik has a spectacular aura about

Re: Need guidance with strchr


what are
CPP / C++ / C Code:
(void*)cp
(int)*sp++
 cout.put( s[i++] );

also look at how null is defined, in C++ it looks like 0 to me :-S

CPP / C++ / C Code:
#ifndef NULL
 #ifdef __cplusplus
  #define NULL  0
 #else
  #define NULL  ((void *)0)
 #endif
#endif 

(footnote: this is getting offtopic, if you want to continue, I can PM you my MSN or Y!M adress, and we can do it there)

PS: just compile this code and run it, tell me what you get .
CPP / C++ / C Code:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    char a,b,c;
    a = '\0';
    b = NULL;
    c = 0;
    if(a==b) cout << "\\0 is the equivalent of NULL"<<endl;
    else cout << "TanLorik offers his sincerest appologises to Howard L"<<endl;
    if( a == c && b == c) cout << "guess what, the ANSI value of 0 is also known as \\0 or NULL"<<endl;
  system("pause");
}
  #9  
Old 21-Nov-2009, 10:20
Howard_L Howard_L is offline
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 932
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: Need guidance with strchr


Yes, the value is zero for both. I said that.
The thing is that '\0' (null) is a char and "NULL" is a pointer. That's why I get the warning.
Read what your textbook says about each (or don't and keep using NULL as you are , sorry)
(is this my son?)
  #10  
Old 21-Nov-2009, 12:03
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,496
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Need guidance with strchr


Quote:
Originally Posted by Howard_L
Yes, the value is zero for both. I said that.
The thing is that '\0' (null) is a char and "NULL" is a pointer. ...

In the C standard:

"The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant."

and

"The macros are
NULL
which expands to an implementation-defined null pointer constant...." (other macros are explained following this.)

In the C++ standard:

"The macro NULL is an implementation-defined C++ null pointer constant..." However, there is an interesting footnote:

"Possible definitions include 0 and 0L, but not (void*)0"

Now what the heck do they mean by that funky footnote???

Well, look it up:

"A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to
zero. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that
type and is distinguishable from every other value of pointer to object or pointer to function type. Two null
pointer values of the same type shall compare equal. The conversion of a null pointer constant to a pointer
to cv-qualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification
conversion."

Try the following:
CPP / C++ / C Code:
#include <stdio.h>

int main()
{
    char *cp = NULL;
    char czero = '\0';

    switch (sizeof(cp)) {
    case 4: 
        printf("This is a 32-bit system");
        break;

    case 8:
        printf("This is a 64-bit system");
        break;

    default: 
        printf("This is a little puzzling: The size of a pointer is %u",
        sizeof(cp));
        break;
    }
    switch(sizeof('\0')) {
        case 1:
            printf(", and this was compiled as a C++ program.\n\n");
            break;

        case 4:
            printf(", and this was compiled as a C program.\n\n");
            break;

        default:
            printf(", and this is a non-standard compiler:");
            printf("The sizeof a character literal is %u\n\n", sizeof('\0'));
    }

    /* Note that compiling with g++ -Wall gives the following message:
       warning: format ‘%p’ expects type ‘void*’, but argument 2 has type ‘int’
       To eliminate the warning in C++, change the %p to %d or %u or %x
     */
    printf("NULL = %p, sizeof(NULL)  = %u\n", NULL, sizeof(NULL));

    printf("cp   = %p, sizeof(cp)    = %u\n", cp, sizeof(cp));
    printf("czero = 0x%02x, sizeof(czero) = %u\n\n", czero, sizeof(czero));
    printf("Note that in C++ the sizeof a char literal is 1,");
    printf(" whereas in C it is 4.\n");
    printf("sizeof('\\0') = %u\n\n", sizeof('\0'));
    return 0;
}

1. Save it as testc.c and compile it with your favorite C compiler.

2. Make a copy named testcpp.cpp and compile it with your favorite C++ compiler.

Output from testc.c from GNU gcc 4.1.2 on a 32-bit Linux system:
Code:
This is a 32-bit system, and this was compiled as a C program. NULL = (nil), sizeof(NULL) = 4 cp = (nil), sizeof(cp) = 4 czero = 0x00, sizeof(czero) = 1 Note that in C++ the sizeof a char literal is 1, whereas in C it is 4. sizeof('\0') = 4

Output from testcpp.cpp compiled with GNU g++ 4.1.2 on a 32-bit Linux sytem:
Code:
This is a 32-bit system, and this was compiled as a C++ program. NULL = 0, sizeof(NULL) = 4 cp = (nil), sizeof(cp) = 4 czero = 0x00, sizeof(czero) = 1 Note that in C++ the sizeof a char literal is 1, whereas in C it is 4. sizeof('\0') = 1


Regards,

Dave
 
 

Recent GIDBlogProblems with the Navy (Enlisted) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Python novice in need of guidance adam_dynamic Python Forum 7 21-Feb-2009 11:17
Complete novice in search or guidance... adam_dynamic Miscellaneous Programming Forum 3 15-Jan-2009 08:22
Some Guidance Needed Logistical Solu Miscellaneous Programming Forum 1 24-Apr-2007 08:06
need guidance : on creating login and shopping cart batrsau Web Design Forum 3 27-Mar-2006 05:53
Guidance on Web Marketing 4-motorcycles Search Engine Optimization Forum 12 29-Apr-2004 19:56

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 19:00.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.