I'm trying to read some information from a .txt file and then store it in a structure, but I don't know how to do it only selecting the words I need.
The .txt is the following
fstream write_messages("C:\\Messages.txt");
A line in the .txt looks like this:
18 [#deniseeee]: hello, how are you? 2016-04-26.23:37:58
So, the thing is that I have a list of strutures
list<Message*> g_messages;
where
struct Message {
static unsigned int s_last_id; // keep track of IDs to assign it automatically
unsigned int id;
string user_name;
string content;
string hour;
Message(const string& a_user_name, const string& a_content) :
user_name(a_user_name), content(a_content), id(++s_last_id), hour(currentDateTime())
{
}
Message(){}
};
I want to read the file so that I can store the number into the id of the list, the word between "[#" and "]:" into the user_name, the next sentence into content and the date into the hour.
How can I do this?
Any help is appreciated
Thank you
The problem is: you are writing this file so it is easy to read by a person, while you should write it so it is easy to load by your program.
You are using spaces to separate your elements, while spaces can very well happen inside those elements.
I would suggest to use a symbol that is not likely to be used in the text, for example the pipe '|'. Also, I would write fixed-size elements first:
18|2016-04-26.23:37:58|deniseeee|hello, how are you?
Then you can read entire line, split it on those pipe symbols and load into your struct fields.
Related
I have a code that save some string to some text (work correctly). I want to concatinate the string to one string and save it to one file in one time.
`np.savetxt(f'{PTH}/pointwise_layer_{number_layer}_channel_{ch}.txt',np.transpose(np.squeeze(layers[number_layer].weights[1][:,:,:,ch],0)))`
I have wrote this code, but it does not work:
pointStr = np.squeeze(layers[number_layer].weights[1][:,:,:,ch],0) + pointStr
Do you know the correct code?
i am fighting with a string splitting. I want to split string by wildcards into a slice, but this slice should contain this wildcards as well.
For example: /applications/{name}/tokens/{name} should be split into [/applications/ {name} /tokens/ {name}] etc.
Here is a sample code i wrote, but it is not working correctly, and i don't feel good about it either.
https://play.golang.org/p/VMOsJeaI4l
There are some example routes to be tested. Method splitPath split path into parts and display both: before and after.
Here is a solution:
var validPathRe = regexp.MustCompile("^(/{[[:alpha:]]+}|/[-_.[:alnum:]]+)+$")
var splitPathRe = regexp.MustCompile("({[[:alpha:]]+}|[-_.[:alnum:]]+)")
func splitPath(path string) parts{
var retPaths parts
if !validPathRe.MatchString(path) {
return retPaths
}
retPaths = splitPathRe.FindAllString(path, -1)
return retPaths
}
I made this by creating two regular expressions, one to check if the path was valid or not, the other to extract the various parts of the path and return them. If the path is not valid it will return an empty list. The return of this will look like this:
splitPath("/path/{to}/your/file.txt")
["path" "{to}" "your" "file.txt"]
This doesn't include the '/' character because you already know that all strings in the return but the last string is a directory and the last string is the file name. Because of the validity check you can assume this.
I have a Stringbuffer object which contains data "Detail is:"
Based on the result of a HashMap(Map), I populate the details below this line with help of looping through the map and fetching data.
Now I want to replace the text "Detail is:" with "Details are:" if more than one record is fetched.
Is their any way to achieve this?
Thanks
You can:
Get the string out of the stringbuffer.
Reset the stringbuffer and write the new beginning.
Write all after the replaced Prefix back to the buffer.
Instead, you could also do this:
Omit the Prefix in the first place
Do a simple string-concatenation at the end.
You can even do like this if Map size is greater than 1
StringBuffer sb=new StringBuffer();
if(map.size>1){
sb.append("Details are:")
}else{
sb.append("Details is:");
}
Is there any method of reading from a text file and omitting certain lines from the output into a text box?.
the text file will look like this
Name=Test Name
Date=19/02/14
Message blurb spanning over several lines
The format will always be the same and the Name & Date will always be the 1st 2 rows and these are the rows that i want to omit and return the rest of the message blurb to a text box.
I know how to use the ReadAllLines function and StreamReader but not sure how to start coding it.
Any pointers or directions to some relevant online documentation?
Thanks in advance
You can read file line by line and just skip lines with given beginnings:
string[] startsToOmit = new string[] { "Name=", "Date=" };
var result = File.ReadLines(path)
.Where(line => !startsToOmit.Any(start => line.StartsWith(start)));
and then you have an IEnumerable<string> as a result, you can use it for example by result.ToList().
Just read the stream line by line:
using (StreamReader sr = new StreamReader(path))
{
Console.WriteLine(sr.ReadLine());
}
Ignore the first two lines, and process the 3rd line however you need.
I've got a problem with data in CSV file to import into Excel.
I've parsed data from a website, and contain line break <br>, I convert this tag into "\n" and write to a CSV file. However, when I import this CSV file into Excel, the line-break display incorrectly. It results new line as a new row instead of a new line in a single cell itself.
Anyone have face this problem before? Really appreciate your suggestion.
Thanks!
Edit: Here the sample to demonstrate my situation
static void TestLine()
{
string sampleData = "日찬양 까페에 올린 충격적인 <br>글코리아타임스";
string formattedData = sampleData.Replace("<br>", "\n");
using (StreamWriter writer = new StreamWriter(#"C:\SampleData.csv", false, Encoding.Unicode))
{
writer.WriteLine(formattedData);
}
}
I want the sampleData displaying in a cell, however, the result happens in 2 cells.
It looks to me like misformated CSV file. To handle this situation correctly, you will need to have a field with line break contained within quotation marks.
UPDATE after the sample:
This works fine:
static void Main(string[] args)
{
string sampleData = "\"日찬양 까페에 올린 충격적인 <br>글코리아타임스\"";
string formattedData = sampleData.Replace("<br>", "\n");
using (StreamWriter writer = new StreamWriter(#"C:\SampleData.csv", false, Encoding.Unicode))
{
writer.WriteLine(formattedData);
}
}
You need to wrap the field in the quotation marks (")
Please take a look at CSV-1203 File Format Specification, in particular the sections on "End-of-Record Marker" and "Field Payload Protection". Hopefully this should give clear guidance on the inner workings of the CSV file format.